joydip_kanjilal
Contributor

Exploring routing in Web API

opinion
Jun 30, 20154 mins
Software Development

Take advantage of routing in Web API to have more control over the URIs for performing the HTTP operations

ASP.Net Web API is a lightweight framework used for building stateless HTTP services. You can use Web API to design and implement RESTful services that run on HTTP. REST is an architectural style — a set of constraints used to implement stateless services. Web API has already become the technology of choice for building light weight HTTP services. In this post, I’ll present a discussion on how routing works in Web API.

When you create a Web API project in Visual Studio, you would observe that a MVC project is created as well. Similar to ASP.Net MVC the routing configuration in a Web API project is invoked from the Global.asax file. A Web API project stores the configuration information in the RouteConfig and WebApiConfig classes — both of these are present in the Application_Start folder. Similar to a MVC project you would observe a RouteConfig.cs file created in the App_Start folder in your solution.

A controller in Web API is responsible for handling HTTP requests. The public methods of the controller are known as action methods. As soon as a request is received, the Web API runtime routes the request to the appropriate action to handle the request. Now, in order to determine which action should be invoked, the Web API runtime takes advantage of a routing table. In contrast to a typical ASP.Net MVC application, the Web API runtime routes the incoming requests to the appropriate controller by matching the HTTP verb of the request to the appropriate action method.

With ASP.Net 5 (to be released soon as part of Visual Studio 2015), there is a unified core framework — you have a single outing framework, a single model binding framework, and a one-filter pipeline. You now have one unified core for ASP.Net MVC, ASP.Net Web API, and ASP.Net Web Pages. So, there’s now only one type of a controller to handle requests: it’s common to your ASP.Net MVC, ASP.Net Web API, and ASP.Net applications.

The default MVC route template looks like this: {controller}/{action}/{id}

In contrast, the default Web API route looks like this:

api/{controller}/{id} The default route created when you create a new Web API project in Visual Studio looks like this: public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } }

Note how the default route is prefixed by “api”. It is a good practice to define the routes of your Web API application by prefixing them with “api” to make them distinct from the standard MVC route. On a different note, when you look at the default route for a Web API project, you wouldn’t see the “{action}” route parameter — the Web API runtime maps requests to the appropriate actions based on the HTTP verb of the requests.

However, you can modify the Web API route definition to include an “{action}” parameter. The following code snippet illustrates how the modified WebApiConfig class looks like.

public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); } }

Now that you have specified “{action}” as part of the route, you need to specify the action when invoking the WebAPI method. Consider the following URL: http://idgservice/authors/1

In this URL, idgservice is the name of the domain where the WebAPI has been hosted, authors is the controller name, and 1 is passed as a parameter. However, this wouldn’t work if you have defined “{action}” in your route definition. You would need to explicitly mention the action name when calling your WebAPI this this case. Here’s the correct URL that includes the action name as part of the URL: http://idgservice/authors/GetAuthorDetails/1

Note that the action name in the above URL is GetAuthorDetails and has been mentioned as part of the modified URL.

You can also specify the HTTP method for an action using the HttpGet, HttpPut, HttpPost, or HttpDelete attribute. The code snippet given below illustrates how this can be achieved:

public class AuthorsController : ApiController { [HttpGet] public Author GetAuthor(id) {} }

If you would like to allow multiple HTTP methods for an action, you can take advantage of the AcceptVerbs attribute as shown below:

public class ProductsController : ApiController { [AcceptVerbs("GET", "HEAD")] public Author GetAuthor(id) { } }

You can also override the action using the ActionName attribute as shown in the code snippet given below:

public class AuthorsController : ApiController { [HttpGet] [ActionName("AuthorDetails")] public Author GetAuthor(id) {} } Note that you can also prevent a method from being invoked as an action by leveraging the NonAction attribute as shown below. public class AuthorsController : ApiController { [HttpGet] [NonAction] public Boolean ValidateLogin(id) {} }

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author