Routing in Web API

If you have worked with MVC routing, you will find out that there are lots of similarities with web API and actually Web API uses the MVC standards on routing. There is only one difference and that's about using HTTP method in web API instead of URL path in MVC. In other word, Web API does not specify an action route parameter, bur it by default maps incoming requests to the appropriate action based upon the HTTP verb of the request.

Take a look at the following sample: 

  1. [HttpPut]
  2. public HttpResponseMessage Order(int Id, OrderDate date)
  3. {
  4.    // Not implement
  5. }

In Order to define a route to this, you would act like this:

  1. config.Routes.MapHttpRoute(
  2.             name: "OrderRoute",
  3.             routeTemplate: "Orders/{Id}/date"
  4.             defaults: new { controller = "Orders", action = "Order" }
  5.         );

The only difference you can find in comparison to MVC, is the using MapHttpRoute() instead of MapRoute(), right? Rather than that Attribute In WebApi2 is like in MVC. if you have visual studio 2013, you can create your Web API2 project template and get start working with attribute routing, otherwise you can get the attribute routing via nuget package manager by executing the below command:

  1. PM> Install-Package AttributeRouting.WebApi

For example, you can define attribute routing for the above sample simply:

  1. [Route("Order/{Id}/date")]
  2. [HttpPut]
  3. public HttpResponseMessage Order(int id, OrderDate)
  4. {
  5. }

Although URL routing in is something extensible, but the routine rules is just what you see in the above. If you are using WebApi2 I advise you to use Attribute routing cause it has lots of advantages and solves lots of troubles of regular routing such as conflicting, readabilities, … . 

For complete information you can refer to this article.

Tags: Asp.Net Web API

comments powered by Disqus