我有以下问题.每当我向Api端点发送邮件时,ASP.NET Core 3.1都无法处理该请求.但是,当我添加 ApiController 属性时,它可以很好地工作.
I have the following issue. Whenever I send something to my Api endpoint, ASP.NET Core 3.1 is not able to process the request. However, when I add the ApiController attribute it works perfectly fine.
我的代码是正确的,但是仅当我添加此属性时有效.怎么样了?
My code is correct but only works when I add this attribute. How is that so?
供参考,这是我的代码
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; });仅供参考,我在ApiController上还有其他使用GET/POST的方法.GET方法工作得很好,但是POST方法仅在我使用查询参数时有效.在这种情况下,我不使用查询参数,因为我要发送给Api的数据比示例中实际提供的要多.
FYI, I have other methods on my ApiController using GET/POST. The GET ones work perfectly fine but the POST methods only work when I use query parameters. In this case, I didn't use query parameters because I have more data to send to my Api than actually given in the example.
我已经尝试使用 [FromBody] 来获得回复.这没用.相反,我得到了空值. foo 甚至都没有实例化.
I've already tried to get my response using [FromBody]. It did not work. I instead got null. foo was not even instantiated.
推荐答案对于将请求主体绑定到模型,有两种类型,一种是从表单数据进行绑定,另一种是 application/json .
For binding request body to model, there are two types, one is binding from form data and the other is application/json.
对于 Controller ,它将默认获取表单数据.对于 ApiController ,它将默认获取json数据.
For Controller,it would fetch the form data by default.For ApiController,it would fetch the json data by default.
如果要绑定请求正文而不使用 [ApiController] ,则可以添加 [FromBody] :
If you want bind request body without using [ApiController],you could add [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... } }型号:
public class SomeClass { public int Id { get; set; } public string Name { get; set; } }查看:
@section Scripts{ <script src="unpkg/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> }结果:
更多推荐
在添加ApiController属性之前,ASP.NET Core 3.1无法处理Axios请求
发布评论