首页 文章

在.NET Core Api 中收到的 Angular POST 请求为 Null

提问于
浏览
0

我通过 Angular 6 发布了一些数据,但是我的 Core API 不断返回空值:

请求:

{"id":0,"name":"test","weight":2,"frequency":2,"activityTypeModelId":3}

响应:

{id: 0, name: null, weight: 0, frequency: 0, activityTypeModelId: 0}

控制器:

[HttpPost("[action]")]
public IActionResult Add([FromForm]Model model)
{
    return new JsonResult(model);
}

Angular,使用 HttpClient:

add(Model: model) {
     return this.http.post(this.addUrl, model);
}

API 模型:

public class Model
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public int Weight { get; set; }
    public int Frequency { get; set; }
    public int ActivityTypeModelId { get; set; }
}

TS 型号:

export class Model{
   id?: number;
   name?: string;
   weight?: number;
   frequency?: number;
   activityTypeModelId?: number;
 }

当我使用 Postman 时,一切正常。我已经尝试了[13]。问题出在哪儿?

3 回答

  • 2

    我不知道为什么,但这解决了我的问题:

    我创建了一个标题:

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

    通过添加标题和 JSON.Stringyfy 对象来更改 POST 功能:

    add(model: Model): Observable<Model> {
         const body = JSON.stringify(c);
         return this.http.post<Model>(this.addUrl, body, { headers: header} );
       }
    

    [FromForm]更改为[FromBody]

    http.post的参数中添加JSON.stringify(model)无效。

    使用 CORE Api 的 JSON:

    {"name":"test","weight":2,"activityTypeModelId":15}

    不使用 CORE Api 的 JSON:

    {name:"test",weight:2,activityTypeModelId:15}

    没有标题我从 API 遇到 415 错误。

  • 0

    尝试

    return this.http.post(this.addUrl, JSON.stringify(model) );
    
  • 0

    我认为,在.NET 核心 2.1 是(见https://docs.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-2.1)

    HttpPost("[action]")]
    //see that I put [FromBody]
    public IActionResult Add([FromBody]Model model)
    {
        //OK is one of several IActionResult 
        return OK(model);
    }
    

相关问题