Attribute Based Routing In ASP.NET Web API And MVC 4

In this article, I will show you how to implement an Attribute Routing in ASP.NET WebAPI. Actually, MVC provides default routing but the developer always wants to customize the route URL as per client requirenment or for ease of understanding.

"WEB Api is just application interface which is used to communicate between client and server. To make communication between them, we need endpoint to use at client side .Web API is a way to transfer data between client and server."

We can easily change the route from default to our own custom pattern and it is called Attribute Routing.



From the image given above, we can understand very easily what is the flow of the route in Web API.
 
Some important links to learn about WebAPI are given below.
Let's create a simple example of WebAPI. If you are following MVC pattern in WebAPI Application, then an end point will be needed. To generate it in a default way, see the code given below.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web.Http;  
  5.   
  6. namespace TestWebApi  
  7. {  
  8.     public static class WebApiConfig  
  9.     {  
  10.         public static void Register(HttpConfiguration config)  
  11.         {  
  12.             config.Routes.MapHttpRoute(  
  13.                 name: "DefaultApi",  
  14.                 routeTemplate: "api/{controller}/{id}",  
  15.                 defaults: new { id = RouteParameter.Optional }  
  16.             );             
  17.         }  
  18.     }  
  19. }  
This part of the code is available inside "App_start" =>"WebApiConfig.config" file. This default route endpoint will look, as shown below in http://localhost:54807/api/CSharp?id=1
 
Attribute routing in WEB API 1

Attribute routing can be thought of as convention based routing. It means the developer can change the route's default pattern to own custom way. Attribute routing is used in the top of an action, controller name in WebAPI and MVC. You are able to set an endpoint according to your pattern given in the link http://localhost:54807/xyz/abc/test/1".
 
How to enable Attribute Routing in WEB API 1

In Web API 1, by default, Attribute Routing is not available, but in Web API 2 Attribute Routing can be used easily without adding external library. Thus, let's go to know how to enable this feature in Web API 1. Create a project, using MVC4 Web Application and select Web API template. For more details, click here. to know how to create.

Go to Solution Explorer=> Right click=> click on "Manage NuGet packages" thereafter new window will open and type "AttributeRouting.Web.Http" in search textbox and press Enter. Afterwards, there are lot of libraries, which will be shown. See the image given below.

 

Select and add in Solution Explorer. Now, you can see "AttributeRoutingHttpConfig.cs"  has been added inside "App_Start " folder. The code part will be added automatically and looks, as shown below. 
  1. using System.Web.Http;  
  2. using AttributeRouting.Web.Http.WebHost;  
  3.   
  4. [assembly: WebActivator.PreApplicationStartMethod(typeof(TestWebApi.AttributeRoutingHttpConfig), "Start")]  
  5.   
  6. namespace TestWebApi   
  7. {  
  8.     public static class AttributeRoutingHttpConfig  
  9.     {  
  10.         public static void RegisterRoutes(HttpRouteCollection routes)   
  11.         {      
  12.             // See http://github.com/mccalltd/AttributeRouting/wiki for more options.  
  13.             // To debug routes locally using the built in ASP.NET development server, go to /routes.axd  
  14.   
  15.             routes.MapHttpAttributeRoutes();  
  16.         }  
  17.   
  18.         public static void Start()   
  19.         {  
  20.             RegisterRoutes(GlobalConfiguration.Configuration.Routes);  
  21.         }  
  22.     }  
  23. }   
Go to controller and add the namespace, where you want use Attribute Routing.
  1. using AttributeRouting.Web.Http;   
  2. using AttributeRouting;   
Types of Attribute Routing
  1. Action based route (HttpRoute).
  2. Controller based route (RoutePrefix).
  3. Area based route (RouteArea).
Controller based routing

Route can be set for the whole controller as a prefix word in an Endpoint. Now, an endpoint is "http://localhost:54807/api/CSharp/test/1 ". See the example given below.
  1. [RoutePrefix("api/CSharp")]  
  2. public class CSharpController: ApiController  
  3. {  
  4.         [HttpGet]  
  5.         [HttpRoute("test/{id}")]  
  6.         public HttpResponseMessage getdata(int ? id)  
  7.     {  
  8.             HttpResponseMessage response = new HttpResponseMessage();  
  9.             DB_DummyMVCEntities _dbcontext = new DB_DummyMVCEntities();  
  10.             var data = from c in _dbcontext.tbl_Employee  
  11.             where c.Id == id  
  12.             select c;  
  13.             if (data != null) {  
  14.                 response = Request.CreateResponse(HttpStatusCode.OK, data);  
  15.             } else {  
  16.                 response = Request.CreateResponse(HttpStatusCode.NotFound, "Data is empty");  
  17.             }  
  18.             return response;  
  19.         }  
Action based routing

Action based route will work separately for a single action.
  1.         [HttpGet]  
  2.         [HttpRoute("/xyz/abc/test/{id}")]  
  3.         public HttpResponseMessage getdata(int? id)  
  4.         {  
  5.   
  6.             HttpResponseMessage response = new HttpResponseMessage();  
  7.             DB_DummyMVCEntities _dbcontext = new DB_DummyMVCEntities();  
  8.   
  9.             var data = from c in _dbcontext.tbl_Employee  
  10.                        where c.Id == id  
  11.                        select c;  
  12.             if (data != null)  
  13.             {  
  14.                 response = Request.CreateResponse(HttpStatusCode.OK, data);  
  15.   
  16.             }  
  17.             else  
  18.             {  
  19.                 response = Request.CreateResponse(HttpStatusCode.NotFound, "Data is empty");  
  20.             }  
  21.             return response;  
  22.   
  23.   
  24.   
  25.         }  
Area based routing

This type of routing is used, if an area is defined in MVC Application. There is no need to use in WebAPI.
  1. [RouteArea("AreaName")]   
Now, I am able to consume an Endpoint method. By Default Route and Attribute Route, the result will be always be the same by both.
See the output given below.



Atttribute Routing is used in WebAPI 1 and WebAPI 2. Also, use it for all verbs(GET,POST,DELETE,PUT).
 
Advantages of an Attribute Routing
  • Endpoint can be customized in its own format.
  • Endpoint can be understand easily for the user.
  • Best practice with WebAPI.
  • Easy for maintenance purpose. 
  • Endpoint looks clean and clear. 
  • Endpoint will be seprate for all actions.
The best practice of coding is to use Attribute Routing.

Up Next
    Ebook Download
    View all
    Learn
    View all