ASP.NET MVC缺省路由通过区域内路由访问
-
26-09-2019 - |
题
到目前为止(为了简洁)我在注册这样的global.asax一条路线:
routes.Add(new LowercaseRoute("{action}/{id}", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new { controller = "Home", action = "Index", id = UrlParameter.Optional }),
DataTokens = rootNamespace
});
其中 “rootNamespace” 是
var rootNamespace = new RouteValueDictionary(new { namespaces = new[] { "MyApp.Web.Controllers" } });
从路线LowercaseRoute继承和只是使小写的所有路径。我还已经注册这样的区域:
context.Routes.Add(new LowercaseRoute("admin/{controller}/{action}/{id}", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new { action = "List", id = UrlParameter.Optional }),
DataTokens = adminNamespace
});
在哪里adminNamespace是另一个命名空间,同样的想法作为默认路由,但正确的命名空间。这工作得很好,我可以访问的URL看起来像这样的:
http://example.com/contact <- default route, "Home" controller
http://example.com/admin/account <- area route, "Account" controller, default "List" action
的问题是,这
http://example.com/admin/home/contact
也有效。有没有“家”控制器下的“管理”区域中的“接触”的动作。它拉右页从“/接触”,但与URL为“/管理/家/接触”。
有什么办法来防止这种情况的发生?
感谢。
解决方案
看一看为AreaRegistrationContext.MapRoute的代码:
public Route MapRoute(string name, string url, object defaults, object constraints, string[] namespaces) {
if (namespaces == null && Namespaces != null) {
namespaces = Namespaces.ToArray();
}
Route route = Routes.MapRoute(name, url, defaults, constraints, namespaces);
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;
}
请注意,尤其是 UseNamespaceFallback 令牌,这是默认设置为false。你需要有类似的逻辑,如果你想将搜索范围限制到该地区的命名空间。 (真=搜索当前命名空间控制器,和如若不然搜索所有名称空间。假=仅搜索当前的命名空间。)
不隶属于 StackOverflow