gpt4 book ai didi

asp.net-mvc-3 - ASP.NET MVC 默认路由可通过区域路由访问

转载 作者:行者123 更新时间:2023-12-03 01:19:21 24 4
gpt4 key购买 nike

到目前为止(为简洁起见)我在 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 继承自 Route,只是将所有路径设为小写。我也有一个这样注册的区域:

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

也有效。在“管理”区域下没有具有“联系”操作的“主” Controller 。它从“/contact”中提取正确的页面,但 URL 为“/admin/home/contact”。

有什么办法可以防止这种情况发生吗?

谢谢。

最佳答案

看一下 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。如果您想将搜索限制在该区域的命名空间内,则需要具有类似的逻辑。 (True = 在当前命名空间中搜索 Controller ,如果失败则搜索所有命名空间。False = 仅搜索当前命名空间。)

关于asp.net-mvc-3 - ASP.NET MVC 默认路由可通过区域路由访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4612279/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com