62,241
社区成员




routes.MapRoute(
name: "BG",
url: "BG/{controller}/{action}/{id}",
defaults: new { Controller = "Admin", action = "Index", id = UrlParameter.Optional },
constraints: new { Url = @"?=BG/.*" }
//constraints: new { Controller = "Admin",url=@"?=BG/.*" }
);
public class LayUIViewEngine:RazorViewEngine
{
public LayUIViewEngine()
{
ViewLocationFormats = new[]
{
"~/Views/{1}/{0}.cshtml",
"~/Views/Shared/{0}.cshtml",
//以上两个是默认视图引擎路径
"~/Views/BG/{1}/{0}.cshtml"//我们的规则
};
}
public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
{
return base.FindView(controllerContext, viewName, masterName, useCache);
}
}
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
RegisterView(); //注册视图子目录
}
protected void RegisterView()
{
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new LayUIViewEngine());
}
}
public class UserAgentConstraint : IRouteConstraint
{
public UserAgentConstraint()
{
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName,
RouteValueDictionary values, RouteDirection routeDirection)
{
return httpContext.Request.Url.ToString().Contains("/BG/") &&
(
values["Controller"].ToString().Equals("Admin",StringComparison.CurrentCultureIgnoreCase) ||
values["Controller"].ToString().Equals("editor", StringComparison.CurrentCultureIgnoreCase)
);
}
}
public class defaultConstraint : IRouteConstraint
{
public defaultConstraint()
{
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName,
RouteValueDictionary values, RouteDirection routeDirection)
{
return values["Controller"].ToString().Equals("Home",StringComparison.CurrentCultureIgnoreCase);
}
}
以上代码定义了两种限制,一种是访问路径里面包含了"/BG/"这个字段并且控制器必须为admin和editor的,另外一个是查看控制器必须为"Home"的
然后把注册路由的函数改为这样:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "BG",
url: "BG/{controller}/{action}/{id}",
defaults: new { Controller = "Admin", action = "Index", id = UrlParameter.Optional },
constraints: new { customConstraint = new UserAgentConstraint()},
namespaces: new string[] { "GGM.Controllers.BG" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { customConstraint = new defaultConstraint() },
namespaces: new string[] { "GGM.Controllers" }
);
}
这样就可以实现了,意思就是如果要匹配到BG那条路由,必须满足UserAgentConstraint 这个类里面定义的条件,下面那个默认路由,必须满足defaultConstraint 这个类的条件。。
但是这样一来就麻烦了,如果要加控制器,那么必须要在对应类的约束条件下多加一条限制语句。。这样其实在多人开发一个项目的时候很不方便。。导致每次提交代码都冲突,git上面需要合并分支才可以,感觉容易出错。。。
那么请问如何才能简单的实现这个功能?