为ASP.NET MVC及WebApi添加路由优先级(2)

public static Configuration RegisterRoutePriority(this Configuration config) { var typesSoFar = new List<Type>(); var assemblies = GetReferencedAssemblies(); foreach (Assembly assembly in assemblies) { var types = assembly.GetTypes().Where(t => typeof(IRouteRegister).IsAssignableFrom(t) && !t.IsAbstract && !t.IsInterface); typesSoFar.AddRange(types); } var context = new RegistrationContext(); foreach (var type in typesSoFar) { var obj = (IRouteRegister)Activator.CreateInstance(type); obj.Register(context); } foreach (var route in context.HttpRoutes.OrderByDescending(x => x.Priority)) GlobalConfiguration.Configuration.Routes.MapHttpRoute(route.Name, route.RouteTemplate, route.Defaults, route.Constraints, route.Handler); foreach (var route in context.Routes.OrderByDescending(x => x.Priority)) RouteTable.Routes.Add(route.Name, route); return config; } private static IEnumerable<Assembly> GetReferencedAssemblies() { var assemblies = BuildManager.GetReferencedAssemblies(); foreach (Assembly assembly in assemblies) yield return assembly; } 这样一来就大功告成,使用时只需要在Global.asax.cs文件中修改原注册入口为 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); Configuration.Instance() .RegisterComponents() .RegisterRoutePriority(); //注册自定义路由 } } 在每个项目中使用只需要要继承自定义路由注册接口IRouteRegister,例如: public class Registration : IRouteRegister { public void Register(RegistrationContext context) { //注册后端管理登录路由 context.MapRoute( name: "Admin_Login", url: "Admin/login", defaults: new { area = "Admin", controller = "Account", action = "Login", id = UrlParameter.Optional }, namespaces: new string[] { "Wenku.Admin.Controllers" }, priority: 11 ); //注册后端管理页面默认路由 context.MapRoute( name: "Admin_default", url: "Admin/{controller}/{action}/{id}", defaults: new { area = "Admin", controller = "Home", action = "Index", id = UrlParameter.Optional }, namespaces: new string[] { "Wenku.Admin.Controllers" }, priority: 10 ); //注册手机访问WebApi路由 context.MapHttpRoute( name: "Mobile_Api", routeTemplate: "api/mobile/{controller}/{action}/{id}", defaults: new { area = "mobile", action = RouteParameter.Optional, id = RouteParameter.Optional, namespaceName = new string[] { "Wenku.Mobile.Http" } }, constraints: new { action = new StartWithConstraint() }, priority: 0 ); } }

四、总结

当遇到大项目注册的路由不生效时你应该要想到有可能是因为路由顺序的原因,以上就是本文的全部内容,希望对大家的学习有所启发。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjwxyw.html