目前,我有如下所示的 URL:
http://www.example.com/user/create
http://www.example.com/user/edit/1
但现在,我必须支持多个组织及其用户。我需要这样的东西:
http://www.example.com/org-name/user/create
http://www.example.com/org-name/user/edit/1
我无法让路由完美地工作,所以我必须在组织名称的开头添加一个标记,这样路由就不会将它与 Controller /操作对混淆。没什么大不了的,但我的 URL 现在看起来像这样:
http://www.example.com/o/org-name/user/create
http://www.example.com/o/org-name/user/edit/1
没关系。我可以接受。
这是我遇到麻烦的地方:
当我选择一个组织后生成 URL 时,它不会保留组织名称。所以当我在这里时:
http://www.example.com/o/org-name
...我使用 Url.Action("User", "Create") 生成一个 URL,它输出:
/user/create
...而不是我想要的:
/o/org-name/user/create
这是我的路线(按顺序):
routes.MapRouteLowercase(
"DefaultOrganization",
"{token}/{organization}/{controller}/{action}/{id}",
new { id = UrlParameter.Optional },
new { token = "o" }
);
routes.MapRouteLowercase(
"OrganizationDashboard",
"{token}/{organization}/{controller}",
new { controller = "Organization", action = "Dashboard" },
new { token = "o" }
);
routes.MapRouteLowercase(
"DefaultSansOrganization",
"{controller}/{action}/{id}",
new { controller = "Core", action="Dashboard", id = UrlParameter.Optional }
);
类似这个问题ASP.NET MVC Custom Routing Long Custom Route not Clicking in my Head .
我觉得这最终会变得显而易见,但现在是星期五,现在还没有发生。
编辑:
Womp 的建议行之有效,但这会是实现自动化的最佳方式吗?
public static string ActionPrepend(this UrlHelper helper, string actionName, string controllerName)
{
string currentUrl = helper.RequestContext.RouteData.Values["url"] as string;
string actionUrl = string.Empty;
if (currentUrl != null)
{
Uri url = new Uri(currentUrl);
if (url.Segments.Length > 2 && url.Segments[1] == "o/")
actionUrl = string.Format("{0}{1}{2}{3}", url.Segments[0], url.Segments[1], url.Segments[2],
helper.Action(actionName, controllerName));
}
if(string.IsNullOrEmpty(actionUrl))
actionUrl = helper.Action(actionName, controllerName);
return actionUrl;
}
编辑:
修复了我的工作路线而不是一起破解它。最终解决方案不需要 URL 中的愚蠢 {token}。也许这会帮助其他人:
routes.MapRouteLowercase(
"Organization",
"{organization}/{controller}/{action}/{id}",
new { controller = "Organization", action = "Dashboard", id = UrlParameter.Optional },
new { organization = @"^(?!User|Account|Report).*$" }
);
routes.MapRouteLowercase(
"Default",
"{controller}/{action}/{id}",
new { controller = "Core", action = "Dashboard", id = UrlParameter.Optional }
);
最佳答案
Url.Action 使用路由值通过查询虚拟路径提供程序并尝试匹配最具体的路由来生成实际的 URL。在您使用的形式中,您正在为 Controller 和操作提供值,这与大多数简单网站一样深入,因此是该方法的方便形式。当Url.Action查询路由系统时,它只有一个“controller”和一个“action”段来匹配。
如果您向该方法提供它需要的其余路由信息,它将正确匹配您想要的路由,并返回正确的 URL。试试这个:
Url.Action("User", "Create", new { token = "o", organization = "organization" })
关于c# - 具有附加一致参数的 ASP.NET MVC 2 路由(不仅仅是 Controller 和操作),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3321339/