Sunday, November 1, 2015

A simple MVC route configuration for RESTFul blog url.

In this article we will configure routing for simple blog application in ASP.NET. The url will follow style of REST based url structure.  Let’s understand the routing for same.

    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "YearAndMonth",
                url: "{controller}/{year}/{month}",
                defaults: new { controller = "post"
                action = "PostByYearAndMonth" }
                );

            routes.MapRoute(
               "PostByYear",
               "{controller}/{year}",
               new { controller = "post", action = "PostByYear" } ,
               new { year = @"\d+" }
            );

            routes.MapRoute(
                "PostByAuthor",
                "{controller}/{name}",
                new { controller = "post"
                action = "PostByAuthor" }, 
                new { name = @"^[a-zA-Z]+$" }
            );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home"
                action = "Index", id = UrlParameter.Optional }
            );
           

        }

    }

We have defined couple of route for different type of request. Here is the controller implementation to support those routes.

public class postController : Controller
    {
        //Get all posts     
        //ex. post
        public ActionResult Index()
        {
            return new EmptyResult();
        }

        //Post by Author name
        //ex. post/sourav
        public ActionResult PostByAuthor(string name)
        {
            return new EmptyResult();
        }

        //Post by year
        //ex. post/2015
        public ActionResult PostByYear(int year)
        {
            return new EmptyResult();
        }

        //post by year and month
        //ex. post/2015/2
        public ActionResult PostByYearAndMonth(int year, int month)
        {
            return new EmptyResult();
        }


    }

Please have a look that routing entry for “PostByYear” taking year parameter which is restricted to integer type and “name” parameter in PostByAuthor is restricted to string. So, when we will pass integer value from route it will hit “PostByYear” action and when the parameter is string type, it will hit to “PostByAuthor” action.


No comments:

Post a Comment