How to add constraints in MVC Route

In my earlier blogs, I wrote about Routing in MVC and ActionResult in MVC
In this blog, I will write about - How to add constraints in MVC routing?
For those who are new to MVC or MVC routing, please read my earlier blogs on MVC

What is Routing in MVC?

Routing is the way to map your action of a controller.  For more details view this blog MVC routing in details.

A default MVC route looks like this, It has a name, url and defaults.
URL section shows the pattern and if pattern matches then corresponding Controller and Action method executed. This is very common MVC routing.


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


Now suppose you want to apply some constraints over the Route.
Means you want to follow specific rule(s) in your URL pattern.

Route Constraints

Route Constraints let you restrict how a parameter in the URL pattern will be matched.


Consider this url - /post/2018/06
Here post published in year 2018 and the publishing month is June.

Now suppose you want to follow a 4 digit year and 2 digit month format in URL.
Means - post/18/6 should not run unless user type this - post/2018/06 and even post/2018/6 is also not ok.

You can manage this by just adding a line in  your route.

Apply Constraints in ASP.NET MVC Route

So, below is your action method in controller -


public class TestController : Controller
    {
        // GET: Test
        public ActionResult PostByDate(int year, int month)
        {
            return Content(string.Format("This post is published in year {0} and month {1}", year, month));
        }
    }


 This is just a standard MVC route for post url. It will match - post/18/06 , post/2018/6, post/2018/06


routes.MapRoute(
                name:"PostYear",
                url:"post/{year}/{month}",
                defaults:new {Controller = "Test", action = "PostByDate" }
                );

 
Now apply constraints on it -

It will match post/2018/06 only


routes.MapRoute(
                "PostYear",
                "post/{year}/{month}",
                 new {Controller = "Test", action = "PostByDate" },
                 new {year=@"\d{4}", month=@"\d{2}"});


 If you want more specific URL pattern

For these 2 URLS - post/2017/06 and post/2018/06
Means only 2017 and 2018  allowed as year parameter in URL to match.


routes.MapRoute(
               "PostYear",
               "post/{year}/{month}",
                new { Controller = "Test", action = "PostByDate" },
                new { year = @"2017|2018", month = @"\d{2}" });

You can apply below constraints to the MVC route -

min, max, minlength, maxlength

Hope this is clear to you? If not, then open Visual Studio and write above code and execute, you will get better understanding over it.

Next -


Happy Learning :)


Comments

Popular

What's new in C# 6.0 language - All new features of C# 6.0 for developers

SharePoint Interview Questions and Answers