Before customizing constraints
namespacemvcapplication2{ Public classRouteconfig { Public Static voidregisterroutes (routecollection routes) {routes. Ignoreroute ("{Resource}.axd/{*pathinfo}"); //defaultroutes. MapRoute (Name:"Default", URL:"{Controller}/{action}/{id}", defaults:New{controller ="Home", action ="Index", id =urlparameter.optional}); } }}
Effect
After customizing constraints
Implementing the Irouteconstraint Interface
usingSystem;usingSystem.Web.Routing;namespacemvcapplication2.extension{ Public classExcludecontroller:irouteconstraint {Private ReadOnly string_controller; PublicExcludecontroller (stringController) {_controller=Controller; } Public BOOLMatch (System.Web.HttpContextBase HttpContext, Route route,stringParameterName, routevaluedictionary values,
Routedirection routedirection) {//returns False if the controller value obtained in the route is equal to the value set by the constraint return!string. Equals (values["Controller"]. ToString (), _controller, stringcomparison.ordinalignorecase); } }}
Route add constraint
usingSYSTEM.WEB.MVC;usingSystem.Web.Routing;usingmvcapplication2.extension;namespacemvcapplication2{ Public classRouteconfig { Public Static voidregisterroutes (routecollection routes) {routes. Ignoreroute ("{Resource}.axd/{*pathinfo}"); //defaultroutes. MapRoute (Name:"Default", URL:"{Controller}/{action}/{id}", defaults:New{controller ="Home", action ="Index", id =urlparameter.optional}, Constraints:New{controller =NewExcludecontroller ("rentalproperties") } ); } }}
Effect
Visible, with the custom constraint, the controller with the Rentalproperties name is limited.
ASP. NET MVC Custom routing-implement Irouteconstraint limit controller name (reprint)