Blog

Filter posts by Category Or Tag of the Blog section!

Routing in asp.net Web API

Thursday, 13 March 2014

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.

Category: Software

Tags: Asp.Net

comments powered by Disqus