Route Constraints in MVC

A few extra concepts of MVC routing

Routing is a great feature of MVC, it provides a REST based URL that is very easy to remember and improves page ranking in search engines.

This article is not an introduction to Routing in MVC, but we will learn a few features of routing and by implementing them we can develop a very flexible and user-friendly application. So, let's start without wasting valuable time.

Add constraint to URL

This is very necessary for when we want to add a specific constraint to our URL. Say, for example we want a URL like this.

http://www.myhost/myconstraint/controller/action

So, we want to set some constraint string after our host name. Fine, let's see how to implement it.

It's very simple to implement, just open the RouteConfig.cs file and you will find the routing definition in that. And modify the routing entry as in the following. We will see that we have added “abc” before.

routing

Controller name, now when we browse we need to specify the string in the URL, as in the following:
 
Controller name

Allow only Integer parameter in controller

Sometimes it is necessary to allow only an integer parameter in an application, to do that we can make a little modification in the routing. Have a look at the following routing entry.
 
Integer parameter in controller

We have specified a pattern for the “id” entry. And the pattern will only allow an integer parameter, not a string or other data type. In that manner we are specifying the URL.
 
url

And it's hitting our targeted action. If we define any other action with some other type id and try to execute that action then it will not call it at all. I am leaving this part for your R&D.

Allow only specific controller or Action

If we wish , we can allow a specific controller or specific action to execute. Again, we need to make a small change in the Route entry. Here is the modified root entry.
 
controller or Action

We will allow only those controllers whose name starts with “H” and only “index” or “Contact” actions are allowed to execute.

So, only the following combination will satisfy.

http://www.hostname/Hone/Index
or
http://www.hostname/Hone/Contact

Conclusion

I hope this article will provide a little extra knowledge of routing of MVC applications. It may provide a little more flexibility in your next applications. Happy reading.

Up Next
    Ebook Download
    View all
    Learn
    View all