【问题标题】:.NET Core API gets null from Angular POST.NET Core API 从 Angular POST 获取 null
【发布时间】:2020-10-20 01:17:21
【问题描述】:

我正在尝试将数据从 Angular 发布到我的 .NET Core API,但传入的 data 始终为空。查看我的代码:

这是我来自 Angular 的 POST:

public insertCategory(categoryToInsert: ICategoryDTO): Observable<ICategoryDTO> {
        const body: string = JSON.stringify(categoryToInsert);
        return this.httpClient.post<ICategoryDTO>(this.apiURL + 'Categories/new', categoryToInsert);
    }

ICategoryDTO 是这样的对象:

export interface ICategoryDTO {
    Id: number;
    Name: string;
}
export default ICategoryDTO;

//exemple object:
{Id: null, Name: "yyuyuy"}

这是我的 API 端点在 .NET Core 端的样子:

[HttpPost("new")]
        [ProducesResponseType(201)]
        [ProducesResponseType(400)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public IActionResult CreateWithAuthor([FromBody] CategoryDTO data)
        {
            var a = 1;
            return Ok(this._iCategoryBusiness.CreateWithAuthor(data));
        }

CategoryDTO 由此类定义:

using System;

namespace Back.DTO
{
    public class CategoryDTO
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

我的问题:我在var a = 1 有一个断点,并且在从我的前端执行帖子时,该断点上的data 总是null。从 Swagger 中进行操作。

我尝试过的:我尝试在传递对象之前对其进行字符串化,但什么也没做。我还尝试将标头与字符串化和非字符串化对象一起传递,但这也不起作用。我将 ICategoryDTO Id 类型从字符串更改为数字,但什么也没做。

这是我尝试过的标题:

header = new HttpHeaders()
    .set('Content-type', 'application/json');

有这样的请求:

public insertCategory(categoryToInsert: ICategoryDTO): Observable<ICategoryDTO> {
        const body: string = JSON.stringify(categoryToInsert);
        return this.httpClient.post<ICategoryDTO>(this.apiURL + 'Categories/new', body, {headers: this.header});
    }

没用,结果一样。

不知道我做错了什么。

【问题讨论】:

  • 在发出 Angular 请求时检查您在 chrome 中的网络选项卡,确保该请求的标头是您所期望的。

标签: c# angular typescript .net-core


【解决方案1】:

我通过使 Id 参数不为空,而是改为 0 来修复它。我想这是有道理的,因为它在 .NET 端不可为空。这花了我两个小时。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    • 2015-07-08
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 2018-01-24
    • 1970-01-01
    相关资源
    最近更新 更多