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

Vin*_*ins 1 javascript ajax model-binding asp.net-core axios

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

我的代码是正确的,但只有当我添加此属性时才有效。怎么会这样呢?

作为参考,这是我的代码

应用程序编程接口

[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;
    }
}
Run Code Online (Sandbox Code Playgroud)

JS

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

}).then(function (response: any) {
   this.Id = response.Id;
});
Run Code Online (Sandbox Code Playgroud)

仅供参考,我的 ApiController 上还有其他使用 GET/POST 的方法。GET 方法工作得很好,但 POST 方法仅在我使用查询参数时才有效。在本例中,我没有使用查询参数,因为要发送到 Api 的数据比示例中实际给出的数据多。

我已经尝试使用 来获得我的回复[FromBody]。它不起作用。相反,我得到了 null。foo甚至没有被实例化。

Ren*_*ena 5

将请求体绑定到模型有两种类型,一种是绑定 from 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...
    }
}
Run Code Online (Sandbox Code Playgroud)

模型:

public class SomeClass 
{
    public int Id { get; set; }
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

看法:

@section Scripts{
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
    axios.post('/api/SomeApi/Add', {
        id: 1,
        name: 'sdfsdf'
    })
        .then(function (response) {
            console.log(response);
        })
        .catch(function (error) {
            console.log(error);
        });
</script>
}
Run Code Online (Sandbox Code Playgroud)

结果: 在此输入图像描述