ASP.NET Core 3.1在添加ApiController属性之前无法处理Axios请求

问题描述 投票:0回答:1

我有以下问题。每当我向Api端点发送邮件时,ASP.NET Core 3.1都无法处理该请求。但是,当我添加ApiController属性时,它可以很好地工作。

我的代码正确,但是仅当我添加此属性时有效。怎么样?

供参考,这是我的代码

API

[ApiController] //Remove this and the code breaks
[Route("api/SomeApi")]
public class ApiController : Controller {

    private readonly IService service;

    public ApiController(IService service)
    {
        this.service = service;
    }

    [HttpPost]
    [Route("Add")]
    public SomeClass Add(SomeClass foo)
    {
        var userId = service.GetCurrentUserId(User);
        foo.Id = Guid.NewGuid();
        foo.UserId = userId;
        service.Add(foo);
        return foo;
    }
}

JS

axios.post('/api/SomeApi/Add', {
   foo: this.foo,

}).then(function (response: any) {
   this.Id = response.Id;
});

FYI,我在ApiController上使用GET / POST的其他方法。 GET的工作原理很好,但是POST方法仅在我使用查询参数时有效。在这种情况下,我不使用查询参数,因为要发送到我的Api的数据比示例中实际提供的要多。

javascript ajax asp.net-core axios model-binding
1个回答
0
投票

对于将请求主体绑定到模型,有两种类型,一种是从form data绑定,另一种是application/json

对于Controller,默认情况下将获取表单数据。对于ApiController,默认情况下将获取json数据。

如果不使用[ApiController]来绑定请求正文,则可以添加[FromBody]

//[ApiController] 
[Route("api/SomeApi")]
public class ApiController : Controller
{
    private readonly IService service;
    public ApiController(IService service)
    {
        this.service = service;
    }

    [HttpPost]
    [Route("Add")]
    public SomeClass Add([FromBody]SomeClass foo)
    {
        //do your stuff...
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.