给Asp.Net MVC及WebApi添加路由优先级
作者:网络转载 发布时间:[ 2015/7/8 11:35:46 ] 推荐标签:测试开发技术
三、具体实现
1、路由定义
public class RoutePriority : Route
{
public string Name { get; set; }
public int Priority { get; set; }
public RoutePriority(string url, IRouteHandler routeHandler)
: base(url,routeHandler)
{
}
}
public class HttpRoutePriority
{
public string Name { get; set; }
public int Priority { get; set; }
public string RouteTemplate{get;set;}
public object Defaults{get;set;}
public object Constraints{get;set;}
public HttpMessageHandler Handler{get;set;}
}
2、定义路由注册的接口
public interface IRouteRegister
{
void Register(RegistrationContext context);
}
3、定义路由注册上下文类
public class RegistrationContext
{
#region mvc
public List<RoutePriority> Routes = new List<RoutePriority>();
public RoutePriority MapRoute(string name, string url,int priority=0)
{
return MapRoute(name, url, (object)null /* defaults */, priority);
}
public RoutePriority MapRoute(string name, string url, object defaults, int priority = 0)
{
return MapRoute(name, url, defaults, (object)null /* constraints */, priority);
}
public RoutePriority MapRoute(string name, string url, object defaults, object constraints, int priority = 0)
{
return MapRoute(name, url, defaults, constraints, null /* namespaces */, priority);
}
public RoutePriority MapRoute(string name, string url, string[] namespaces, int priority = 0)
{
return MapRoute(name, url, (object)null /* defaults */, namespaces, priority);
}
public RoutePriority MapRoute(string name, string url, object defaults, string[] namespaces,int priority=0)
{
return MapRoute(name, url, defaults, null /* constraints */, namespaces, priority);
}
public RoutePriority MapRoute(string name, string url, object defaults, object constraints, string[] namespaces, int priority = 0)
{
var route = MapPriorityRoute(name, url, defaults, constraints, namespaces, priority);
var areaName = GetAreaName(defaults);
route.DataTokens["area"] = areaName;
// disabling the namespace lookup fallback mechanism keeps this areas from accidentally picking up
// controllers belonging to other areas
bool useNamespaceFallback = (namespaces == null || namespaces.Length == 0);
route.DataTokens["UseNamespaceFallback"] = useNamespaceFallback;
return route;
}
private static string GetAreaName(object defaults)
{
if (defaults != null)
{
var property = defaults.GetType().GetProperty("area");
if (property != null)
return (string)property.GetValue(defaults, null);
}
return null;
}
private RoutePriority MapPriorityRoute(string name, string url, object defaults, object constraints, string[] namespaces,int priority)
{
if (url == null)
{
throw new ArgumentNullException("url");
}
var route = new RoutePriority(url, new MvcRouteHandler())
{
Name = name,
Priority = priority,
Defaults = CreateRouteValueDictionary(defaults),
Constraints = CreateRouteValueDictionary(constraints),
DataTokens = new RouteValueDictionary()
};
if ((namespaces != null) && (namespaces.Length > 0))
{
route.DataTokens["Namespaces"] = namespaces;
}
Routes.Add(route);
return route;
}
private static RouteValueDictionary CreateRouteValueDictionary(object values)
{
var dictionary = values as IDictionary<string, object>;
if (dictionary != null)
{
return new RouteValueDictionary(dictionary);
}
return new RouteValueDictionary(values);
}
#endregion
#region http
public List<HttpRoutePriority> HttpRoutes = new List<HttpRoutePriority>();
public HttpRoutePriority MapHttpRoute(string name, string routeTemplate, int priority = 0)
{
return MapHttpRoute(name, routeTemplate, defaults: null, constraints: null, handler: null, priority: priority);
}
public HttpRoutePriority MapHttpRoute(string name, string routeTemplate, object defaults, int priority = 0)
{
return MapHttpRoute(name, routeTemplate, defaults, constraints: null, handler: null, priority: priority);
}
public HttpRoutePriority MapHttpRoute(string name, string routeTemplate, object defaults, object constraints, int priority = 0)
{
return MapHttpRoute(name, routeTemplate, defaults, constraints, handler: null, priority: priority);
}
public HttpRoutePriority MapHttpRoute(string name, string routeTemplate, object defaults, object constraints, HttpMessageHandler handler, int priority = 0)
{
var httpRoute = new HttpRoutePriority();
httpRoute.Name = name;
httpRoute.RouteTemplate = routeTemplate;
httpRoute.Defaults = defaults;
httpRoute.Constraints = constraints;
httpRoute.Handler = handler;
httpRoute.Priority = priority;
HttpRoutes.Add(httpRoute);
return httpRoute;
}
#endregion
}
4、把路由注册处理方法添加到Configuration类中
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
);
}
}
四、总结
这是一个对Asp.Net Mvc的一个很小的功能拓展,小项目可能不太需要这个功能,但有时候项目大了注册的路由不生效时你应该要想到有可能是因为路由顺序的原因,这时这个路由优先级的功能有可能会给你带来便利。总之共享给有需要的朋友们参考。
本文内容不用于商业目的,如涉及知识产权问题,请权利人联系SPASVO小编(021-61079698-8054),我们将立即处理,马上删除。
相关推荐
Asp.net MVC如何对所有用户输入的字符串字段做Trim处理Asp.Net WebForm生命周期的详解asp.net 六大内置对象Linux使用Jexus托管Asp.Net Core应用程序asp.net登录验证码实现方法ASP.NET自带对象JSON字符串与实体类的转换ASP.NET MVC必须知道的那些事!Asp.net Core MVC中使用SessionASP.NET Core的配置(7):多样性的配置来源[下篇]ASP.NET Core的配置(6):多样性的配置来源[中篇]ASP.NET Core的配置(5):多样性的配置来源ASP.NET实现License Key输入功能ASP.NET Core 1.0中的管道-中间件模式ASP.NET Core的配置(3): 将配置绑定为对象[上篇]ASP.NET Core的配置(2):配置模型详解ASP.NET中的随机密码生成
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11热门文章
常见的移动App Bug??崩溃的测试用例设计如何用Jmeter做压力测试QC使用说明APP压力测试入门教程移动app测试中的主要问题jenkins+testng+ant+webdriver持续集成测试使用JMeter进行HTTP负载测试Selenium 2.0 WebDriver 使用指南