First, why the need for routing priority
We all know that we have no priority in registering routes in the ASP.net MVC project or Webapi project, when the project is larger, has multiple zones, or multiple Web projects, or is developed with a plug-in framework, our route registration is probably not written in one file, Instead, they are scattered across a number of different projects, so that the priority of the routing problem is highlighted.
For example: in App_start/routeconfig.cs
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Areas/Admin/AdminAreaRegistration.cs
context.MapRoute(
name: "Login",
url: "login",
defaults: new { area = "Admin", controller = "Account", action = "Login", id = UrlParameter.Optional },
namespaces: new string[] { "Wenku.Admin.Controllers" }
);
If you register the above generic default route and then register the login route, you will first match the first route that satisfies the condition, that is, the two route registration is invalid.
This problem is caused by the sequence of these two routing registrations, and there is no priority to registering routes in asp.net mvc and webapi, so today we are going to implement this idea ourselves by adding a priority concept when registering a route.
Second, the solution to the idea
1, first analysis of the route registration portal, such as we create a new mvc4.0 project
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
There are two registered entries for the MVC route:
A. Arearegistration.registerallareas (); Registering area routes
B. routeconfig.registerroutes (routetable.routes); Registering Project Routes
There is a WEBAPI route registration entry:
Webapiconfig.register (globalconfiguration.configuration); Registering WEBAPI Routing
2, the Registration route processing class analysis
AreaRegistrationContext
RouteCollection
Httproutecollection
When you register a route, these three classes are primarily registered to handle the route.
3. Route priority scheme
A, change the registration entry for the route
b, customize the structure class routepriority and httproutepriority of a route, these two classes have priority this property
C, custom a registrationcontext to register the route, the registered object for the above custom route.
D, after all the routing registrations are completed and then added to RouteCollection and httproutecollection in the order of precedence, it actually takes effect.