标签:style blog http io ar color os sp for
有时候我们会碰到两个项目合在一起,那么必然会碰到两个同名的controller,其实MVC在注册路由,添加Route的时候可以指定当前规则解析那个命名空间下的所有Controller。
注:Controller的调用是通过IControllerFactory,反射调用目标Controller,不指定目标命名空间,直接从BuildManager.GetReferencedAssemblies();如下。
private static List<Type> controllerTypes = new List<Type>(); /// <summary> /// 静态构造函数 /// </summary> static DefaultControllerFactory() { var assemblys = BuildManager.GetReferencedAssemblies(); foreach (Assembly assembly in assemblys) { var types = assembly.GetTypes().Where(a => typeof(IController).IsAssignableFrom(a)); foreach (Type type in types) { controllerTypes.Add(type); } } } /// <summary> /// 创建controller /// </summary> /// <param name="requestContext"></param> /// <param name="controllerName"></param> /// <returns></returns> public IController CreateController(RequestContext requestContext, string controllerName) { string typeName = controllerName + "Controller"; Type controllerType = controllerTypes.FirstOrDefault(a => a.Name == typeName); if (controllerType != null) { return (IController)Activator.CreateInstance(controllerType); } return null; }
回归正题:如何支持多种命名空间
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}", defaults: new { controller = "Home", action = "Index" }, namespaces: new string[] { "MvcExpose.Controllers" } ); routes.MapRoute("Admin", "Admin/{controller}/{action}", new { controller = "Home", action = "Index"}, new string[] { "MvcExpose.Admin.Controllers" }); }
切记:两种注册Url规则,要长度不一致,Default带有"{controller}/{action}/{id}"一直报错,以为在正则解析看来,无法区分两种路由规则的区别,因此当“http://localhost:4500/Admin/Home/Index”,系统先调用default的路由解析。
标签:style blog http io ar color os sp for
原文地址:http://www.cnblogs.com/cainiaoguoshi/p/4150097.html