How to implement Route constraints Concepts in mvc application

By
Route constraints is a way to put some validation rules in a defined route. This is very useful concepts in asp.net mvc application.You can apply Route constraints according to your requirements.Your mvc application will be run after performed the validation steps. 
Why does we use it:- 
Any unauthorized user can't access your mvc application. 
Example :-
Suppose we have defined following rules (route path) in your mvc application.If you want to restrict the incoming url with numeric id.then we will have to apply this constraints in your Global.asax file in your mvc application.
1.)  Here first i will show you that there is no restriction in incoming request url as shown below:-
public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", 
                    action = "Index", 
                    id = UrlParameter.Optional } // Parameter defaults
            );

        }

2.) Creating Route constraints:- 
Here i will show you "How to create Route constraints in mvc application". Here i will restrict the url parameter with numeric value as shown below:- 
public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Bollywood", 
                    action = "Images", 
                    id = UrlParameter.Optional },// Parameter defaults
            new {id =@"\d+"} // Restrict Numeric Id
                    );

        }
Descriptions:-
1.) If you are using example number 1 codes , there is no Route constraints .Means you access any url like  http://mysite.com/Bollywood/images/10
Here you will see no error  message if this image id 10 exists in your  mvc application. 
2.) If you are using  example number 2 codes, here i have putted a Route constraints on Id parameter with numeric value (  new {id =@"\d+"}). Means you can't use numeric value in your URL  like
 http://mysite.com/Bollywood/images/10
this URL will show an error message that you can't use numeric value with URL Parameter.
If you want to understand the  Complete Route concepts see here

0 comments:

Post a Comment

Powered by Blogger.