Tuesday 28 July 2015

URL Rewriting in MVC 4 (attribute routing)



Now we are going to discuss about url rewring using web API's . According to new release of Web API2 , they implemented new type of url rewring called as 'attribute routing' which uses attribute to define routes. Attribute routing gives you more controle over URLs. Using this you can easly creates uls that defines your resouce heirarchi

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

/customers/1/orders

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

[Route("customers/{customerId}/orders")]
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)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}

and in your controller add the Route attributes

public class OrdersController : Controller
{
    [Route("customers/{customerId}/orders")]
    [HttpGet]
    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)


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

No comments:

Post a Comment