URL Rewriting in MVC 4 (attribute routing) - International Days

International Days

Internationally important Days


Home Top Ad

Post Top Ad

Tuesday, 28 July 2015

URL Rewriting in MVC 4 (attribute routing)

Now we are going to discuss about url rewriting using web API's . According to new release of Web API2 , they implemented new type of url rewritng called as 'attribute routing' which uses attribute to define routes. Attribute routing gives you more control over URLs. Using this you can easily creates urls that defines your resource hierarchic

Before attribute routing Web-APIs use convention-base routing which is not able to support all kinds of url structure for example the below type of urls


This type of urls which is difficult to create using convention-base routing
But it is very easy to create with attribute routing you can simple give the structure as attributes like below

public IEnumerable<Order> GetOrdersByCustomer(int customerId) { ... }

For enabling the attribute routing need to add the following code ton WebApiConfig class which is fount in App_start folder

public static class WebApiConfig
public static void Register(HttpConfiguration config)
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }

and in your controller add the Route attributes

public class OrdersController : Controller
    public IEnumerable<Order> FindOrdersByCustomer(int customerId) { ... }

Note:- if Route trhrows exception , then you need to install new web api pakages for mvc
Install-Package AttributeRouting (for MVC)

Optional Parameter 
We can also add optional parameter to the attribute routing  . For that purpose we only have to do is
just add a question mark to the routing parameter which is optional please refer the example given below

public ActionResult search(string KeyId, string Keyword, string LocationID, string Location)

Please leave your comment ,It will be help full to improve my Blog


Post Bottom Ad