Using axios.post for send a simple value int to my controller on asp.net core, when send any value ever the method controller receive value "0".
Which is the correct way for send this type of value using axios (post or delete)?
PD: i can send correctly models and receive on controller with [FromBody]
Method controller:
[Route("Delete"),HttpPost]
public async Task<ActionResult> Delete(int id)
{
try{
var result = await userService.DeleteUserPerson(id);
return Json(new{
response=true,
data=result,
error=""
});
}
catch(Exception ex){
return Json(new{
response=false,
data=false,
error=ex.Message
});
}
}
Method from react class:
async function DeleteUser(id, props){
var request= new Request({});
try{
console.log(id);
var axiosResp= await request.axios_request.post('User/Delete', JSON.stringify({id:id}));
if(axiosResp.status!=200){
//do smething
}
//this case validate error
if(axiosResp.data.response && !axiosResp.data.error){
//do something
}
//do something
}catch(err){
//do something
}
}
Class request (axios):
export default class Request {
constructor(){
this.axios_request = axios.create({
baseURL: 'http://localhost:5000/api',
timeout: 5000,
headers: authHeader()
});
}
}
Testing diferents ways, this work for me:
[Route("Delete/{id}"),HttpDelete("{id}")]
public async Task<ActionResult> Delete([FromRoute]int id){}
On axios use delete:
request.axios_request.post('User/Delete/'+ id);
It looks like you are trying to do two different things at once. So you can either specify the id in route or in the body of the HTTP request. If it is in the route the url which should be called is "User/Delete/{id}". In that case you should specify [FromRoute] before the id parameter of the function "Delete". like this (I would recommend using the HTTP delete for this: you can read about using delete with axios here: Axios Delete request with body and headers?):
[Route("Delete")]
[HttpDelete]
public async Task<ActionResult> Delete([FromRoute] int id)
If you want to specify the id in the body you should do, as you mention yourself, use the [FromBody] like this:
[Route("Delete")]
[HttpPost]
public async Task<ActionResult> Delete([FromBody] int id)
If you want to delete a model then I would suggest actually using the HTTP method delete instead. You should then use the decorator [HttpDelete] instead of [HttpPost] as shown above.
Edit: Furthermore I can see that you are sending an object containing the parameter id to the controller. Try either just sending the number or change the parameter of the function to an object containing the id to match what you are sending in your axios call.
This means changing this line:
var axiosResp= await request.axios_request.post('User/Delete', JSON.stringify({id:id}));
to:
var axiosResp= await request.axios_request.post('User/Delete', id);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With