Ehsan Ghanbari

Experience, DotNet, Solutions

Routing in asp.net Web API

If you have worked with asp.net MVC routing, you will find out that there are lots of similarities with asp.net 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: 

[HttpPut]

public HttpResponseMessage Order(int Id, OrderDate date)

{

   // Not implement

}

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

config.Routes.MapHttpRoute(

            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:

[Route("Order/{Id}/date")]

[HttpPut]

public HttpResponseMessage Order(int id, OrderDate)

{

}

Although URL routing in asp.net 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. I spend a lot of time on software architecture. Since 2008, I've been as a developer for different companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the past years, Read More

Post Tags
Pending Blog Posts
using Elmah in asp.net MVC4
Using FluentSecurity in MVC
Strategic design
Factory Pattern
time out pattern in ajax
Redis as a cache server
How to use PagedList In asp.net MVC
Multiple submit buttons in asp.net MVC
Domain driven design VS model driven architecture
What's the DDD-lite?
comments powered by Disqus