By default, In MVC Web API, the route configuration follows RESTFUL conventions meaning that it will accept only the Get, Post, Put and Delete action names. However for better readability a developer will definitely feel the need for his own meaning action names. In this blog, I will explain how to implement custom action names.
1. Let's first create a simple web API. Create ASP.NET MVC4 project by selecting the Web API project template.
2. By default valuescontroller and home controller is added as part of solution.
3. Following methods are added to values controller.
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "helloss yogita";
}
3. Run the project, type the url "http://localhost:56355/api/values/" in addess bar. Here is the response.
4. Similarly, now type the url "http://localhost:56355/api/values/5" and observe the response.
5. Now, these methods are standard methods. But usually, a developer would like to give more logical and meaningful method names. For example, action name Get doesn't reveal much information about what kind of information is returned from a particular action. Let's say I want to call an action GetContactInfo(string id) where id can be EmployeeId.
6. Let's write a method now, in values controller which accepts a Id and returns contact information.
public string GetContactInformation(string id)
{
return "Contact number is 1234567890";
}
7. Now run the project to see what's is returned as output of this method. Type this url "http://localhost:56355/apis/values/GetContactInfo/5"
Oops!!! Ok, this happened because, Web API routing is not aware of this route.
8. Let's fix it. App_Start->WebApiConfig.cs and provide the route information.
//declare the route handler for contacts api to handle CustomActionMethod GetContactInfo
config.Routes.MapHttpRoute(
name: "ContactsApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
9. Now, we have mapped the route handler with controller and action methods. Now run the project and try
Oops!! Its not finding the resource again.
10. Let's be more specific and provide the actionname information is web uri template as follows.
//declare the route handler for contacts api to handle CustomActionMethod GetContactInfo
config.Routes.MapHttpRoute(
name: "ContactsApi",
routeTemplate: "api/{controller}/{GetContactInformation}/{id}",
defaults: new { id = RouteParameter.Optional }
);
11. Let's run the URL again. And observe the output.
Therefore we saw how we can use meaningful action names and map them using Web API routing template.