问题
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?
For reference, here's my code
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, 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.
I've already tried to get my response using [FromBody]
. It did not work. I instead got null. foo
was not even instantiated.
回答1:
For binding request body to model, there are two types, one is binding from form data
and the other is application/json
.
For Controller
,it would fetch the form data by default.For ApiController
,it would fetch the json data by default.
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...
}
}
Model:
public class SomeClass
{
public int Id { get; set; }
public string Name { get; set; }
}
View:
@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>
}
Result:
回答2:
I had the same problem and solved it using qs library for stringifying the JSON Object.
axios.post('/controller/action', Qs.stringify({Id: 1, Name: 'Test'}))
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
Another way that worked for plain objects is using URLSearchParams.
var requestData = {Id: 1, Name: 'Test'}
var params = new URLSearchParams();
for(key in requestData)
params.append(key, requestData[key]);
axios.post('/controller/action', params)
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
来源:https://stackoverflow.com/questions/59824953/asp-net-core-3-1-cannot-process-axios-request-until-apicontroller-attribute-is-a