3

I have .net core WebApi like below. And it is working perfectly. But, when I write [HttpDelete] instead of [HttpDelete("{id}")] , then it doesn't work. What can be reason ?

My url : http://localhost:5004/api/Student/DeleteStudent/23

[ApiController]
[Route("api/[controller]/[action]")]
public class StudentController : ControllerBase
{
    //[HttpDelete] ///////////////// This is not working
    [HttpDelete("{id}")] /////////// This is working
    public async Task<ServiceResult> DeleteStudent(int id)
    {
      return await studentService.DeleteStudent(id);
    }
}
5
  • 2
    How will MVC know where to get the ID from? Why do you want to remove the routing template? Commented Nov 27, 2018 at 11:31
  • I'm sending only one parameter. I thought, it can know @PanagiotisKanavos Commented Nov 27, 2018 at 11:33
  • Forexample in this site ; c-sharpcorner.com/article/… @PanagiotisKanavos He didn't use id parameter. Commented Nov 27, 2018 at 11:37
  • without the id route template parameter, that only other way to populate the value would be via query string (ie http://localhost:5004/api/Student/DeleteStudent?id=23). Either way, the id needs to be provided to know which record to delete Commented Nov 27, 2018 at 11:37
  • Thanks @ Nkosi. I think, this is what I'm looking for. It worked. Can you write as answer and I will mark as an answer. Commented Nov 27, 2018 at 11:42

2 Answers 2

4

Without the {id} route template parameter, the only other way to populate the value would be via query string

http://localhost:5004/api/Student/DeleteStudent?id=23 

The route table will match the querystring parameter to the action parameter to make the match.

Either way, the id needs to be provided to know which action to call and which record to delete.

Sign up to request clarification or add additional context in comments.

Comments

0

You have to tell the router about your api signature.. now by replacing [HttpDelete("{id}")] by [HttpDelete] your signature become api/[controller]/[action], thus your router will ignore anything after that signature.

You can define custom route if you like to leave it as [HttpDelete] where you will also specify id as a parameter.

1 Comment

Thanks @MichelHanna. Nkosi's answer solved my issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.