Ehsan Ghanbari

Experience, DotNet, Solutions

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: 


public HttpResponseMessage Order(int Id, OrderDate date)


   // Not implement


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


            name: "OrderRoute",

            routeTemplate: "Orders/{Id}/date"

            defaults: new { controller = "Orders", action = "Order" }


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 started working with attribute routing, otherwise, you can get the attribute routing via NuGet package manager by executing the below command:

PM> Install-Package AttributeRouting.WebApi

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



public HttpResponseMessage Order(int id, OrderDate)



Although URL routing in is something extensible, the routing rules are 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.

About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
Peridic pattern
How to use PagedList In MVC
Redis as a cache server
Domain driven design VS model driven architecture
How to query over Icollection<> of a type with linq
What's the DDD-lite?
comments powered by Disqus