Action methods are selected in WebAPI based on the HTTP method used to make the request.This means that if HTTP GET method is used to make the request then action methods whose names are beginning with Get are selected.For example following action method will handle HTTP GET requests :
public Product GetStudentById(id) { }
However sometimes we need to name our action methods differently.In such a scenario we can include specific attributes while declaring action methods.In this case action method will be selected based on the attribute used to declare the action method.Following are some of the useful attributes :
HttpGet | Maps the HTTP get requests to the action method |
HttpPut | Maps the HTTP put requests to the action method |
HttpPost | Maps the HTTP post requests to the action method |
HttpDelete | Maps the HTTP delete requests to the action method |
AcceptVerbs | Maps the specified HTTP methods to the action method |
In the following example action method is called FindStudentById. Though the action method does not include get in its name it will still handle the HTTP GET requests because it is declared with the attribute [HttpGet]
[HttpGet] public Product FindStudentById(id) { }
Below action method will handle the POST requests :
[HttpPost] public Product FindStudentById(id) { }
Specifying multiple HTTP verbs
We can specify multiple HTTP verbs for a single action method using AcceptVerbs attribute.We pass the verbs to the attribute as a comma separated values.
Following action method will handle both the put and post requests.This is because the get and put values are specified while declaring the attribute
[AcceptVerbs("POST", "PUT")] public Product UpdateStudent(StudentViewModel vm) { }
Leave a Reply