Application example of routing IRouteConstraint method in ASP.NET MVC

In the writing of the following code:

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
       routes.MapPageRoute("Report", "report", "~/Content/page/report.aspx")
       routes.MapRoute( name: "BaseManage", url: "Admin/BaseManage/{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); 
       routes.MapRoute( name:
"Order", url: "Admin/OrderManage/{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );
       routes.MapRoute( name:
"Admin", url: "Admin/{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );
       routes.MapRoute( name:
"Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id =UrlParameter.Optional});
     }
  }

Because the system needs, the MapPageRoute and MapRoute methods are applied in the method RegisterRoutes at the same time. The consequence of this is that all pages are jumped to the WEBFORM page when they are loaded, resulting in the system reporting an error.

The reason for the error is that there is a conflict between the two different methods. To solve this problem, you need to add a constraint to MapPageRoute. At this time, the IRouteConstraint interface is used. See the following code:

public class MyCustomConstraint : IRouteConstraint
    {
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            return routeDirection == RouteDirection.IncomingRequest;
        }
    }

Then modify the statement as follows

//routes.MapPageRoute("Report", "report", "~/Content/page/report.aspx");
routes.MapPageRoute("Report", "report", "~/Content/page/report.aspx", true, null, new RouteValueDictionary { { "outgoing", new MyCustomConstraint() } });

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326371094&siteId=291194637