Saturday, November 15, 2014

Specify Route Name to implement smart routing in Web API 2.0

We know the feature of Attributing routing in Web API 2.0,that gives more flexible routing mechanism on top of MVC routing.

Using Attributing routing we can specify each action with a unique route template and we can tag unique name to the template. The naming of each route template is not mandatory but ASP.NET MVC environment assign a unique name to each route template if we do not specify explicitly.


Now, the question is! What is the advantage of tagging unique name in route template? In this article, we will discuss one good advantage of naming of route.

namespace WebAPI.Controllers
{
   public class blog
   {
       public int Id { get; set; }
       public string Title { get; set; }
   }

    public class BlogController : ApiController
    {
        List<blog> blogCollection = new List<blog>();

        [Route("show/blog/id", Name="ShowBlogById")]
        public blog Get(Int32 id)
        {
            return blogCollection[id];
        }
       
        public HttpResponseMessage Post(blog blog)
        {
            blogCollection.Add(blog);
            //You may choose some other storage rather than In-memory collection

            var response = Request.CreateResponse(System.Net.HttpStatusCode.Created);
            string Uri = Url.Link("ShowBlogById", new { Id = blog.Id});
            response.Headers.Location = new Uri(Uri);
            return response;
        }

    }
}

In example we have defined blog model and using same model in both Get() and Post() actions. Have a look that Get() action is routed with this routing template.

“show/blog/id”

In addition, we have specified the routing name as “ShowBlogById”.  Now, have a look into body of Post() action.  When we are creating response object we are attaching header location by mentioning the route name of Get() action.

Now, let’s see how HTTP response comes after insertion of any model.


We are seeing that the status code is 201 means Created and the location of new resource is highlighted.  
Now, if we click on the link, it will redirect us to Get() action 


So, the advantage is that In time of resource location creation in Post() we did not specify actual path of created resource rather we specified the route name.




No comments:

Post a Comment