Asp.net mvc journey-powerful custom IRouteConstraint constraints in the third-site routing template,

Source: Internet
Author: User

Asp.net mvc journey-powerful custom IRouteConstraint constraints in the third-site routing template,

When writing mvc, we often configure various url templates, such as controller, action, and id combination modes. In fact, we can also separately configure these three parameters, the method is natural

Is the constraints attribute in MapRoute.

 

I. Simple Regular Expression matching

Regular Expression matching is the simplest method. For example, for the value of id in the preceding route, I can use regular expressions to limit the value. That is to say, the id can only be an integer. Can this be done ??? For highly scalable mvc,

Of course, this can be done, as shown below:

            routes.MapRoute(                name: "Default",                url: "{controller}/{action}/{id}",                defaults: new { controller = "Home", action = "Index" },                constraints: new { id = @"\d+" }            );

 

Then, I enter a correct url. The effect is as follows.

 

When I change the id to abc, the effect is like this ....

 

Awesome, the page can no longer be opened, isn't it very happy, then there is hanging hair to find you, this id limit can be more powerful, according to the database configuration, or third-party logic to show whether or not to display,

This is not a tragedy. The current id seems to only have regular expression matching. It seems that it cannot be powerful enough to control the id value in the Custom logic, but don't be discouraged. As I said just now, mvc is a highly scalable framework,

You can solve this problem yourself.

 

Ii. IRouteConstraint powerful custom logic verification

You can see that IRouteConstraint is an interface and its definition is as follows:

1 // 2 // Summary: 3 // The definition class must be implemented to check whether a URL parameter value is valid for the constraint. 4 [TypeForwardedFrom ("System. web. routing, Version = 3.5.0.0, Culture = Neutral, PublicKeyToken = 31bf3856ad364e35 ")] 5 public interface IRouteConstraint 6 {7 // 8 // Abstract: 9 // determine whether the URL parameter contains the valid values of this constraint. 10 // 11 // parameter: 12 // httpContext: 13 // an object that encapsulates information about HTTP requests. 14 // 15 // route: 16 // object to which the constraint belongs. 17 // 18 // parameterName: 19 // name of the parameter being checked. 20 // 21 // values: 22 // an object containing URL parameters. 23 // 24 // routeDirection: 25 // an object that indicates whether a constraint check is being executed when an incoming request is processed or a URL is generated. 26 // 27 // return result: 28 // true if the URL parameter contains a valid value; otherwise, false. 29 bool Match (HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection); 30}

 

In this interface, a Match method is provided, and all I need to do is implement a class that inherits it. If true is returned, it means pass, and if false is returned, the matching fails .... Just like what I do now

Such bad code:

1 public class RouteConfig 2 {3 public static void RegisterRoutes (RouteCollection routes) 4 {5 routes. ignoreRoute ("{resource }. axd/{* pathInfo} "); 6 7 routes. mapRoute (8 name: "Default", 9 url: "{controller}/{action}/{id}", 10 defaults: new {controller = "Home ", action = "Index"}, 11 constraints: new {id = new MyRouteConstraint ()} 12); 13} 14} 15 16 public class MyRouteConstraint: IRouteConstrain T17 {18 public bool Match (HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 19 {20 // obtain the value of id 21 var id = values [parameterName]; 22 23 // logic... 24 25 return true; 26} 27}

 

Let's see it clearly... In the Match method of MyRouteConstraint class I implemented, I can use values [parameterName] to successfully obtain the id value. If not, I can debug it for my reference...

After you get this value, you can play freely...

 

3. Source Code Analysis

So far, are you curious about how this fake thing works .... It's actually very easy. I still remember the concept of routing in various mvc getting started books... Actually

Route class... As shown below.

 

In the Route class, the most important thing is the GetRouteData method, which is used to determine whether you can view the mood to send your http request to the Controller... Then let's take a look.

Source code of this method...

 

In the end, the two core pieces of code are shown in front of you.

1. constraint as IRouteConstraint if it is of the IRouteConstraint type, use the matching method implemented by me.

2. constraint as string follows my regular match, for example, Regex. IsMatch ....

 

Well, I will talk about it here, hoping to help you.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.