Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
75
rated 0 times [  78] [ 3]  / answers: 1 / hits: 5764  / 4 Years ago, mon, january 20, 2020, 12:00:00

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.


More From » ajax

 Answers
5

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:
enter


[#5001] Thursday, January 16, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ariel

Total Points: 523
Total Questions: 111
Total Answers: 100

Location: Anguilla
Member since Sun, Jan 29, 2023
1 Year ago
ariel questions
;