如何分隔路径相同但功能不同的路线? [英] How do I separate routes that have the same path but do different things?
问题描述
以下路由 Page/View/Id
将转到页面控制器"中的 View
方法.我还想要以下路线:
The following route Page/View/Id
would go to the View
Method in the Page Controller. I'd also like the following route:
/{page-title}
转到相同的方法.这样一来,我可以拥有类似以下的网址:
to go to the same method. That's so I could have URLs like the following:
http://www.mysite.com/This-Is-a-Page
考虑 This-Is-a-Page
也可能是控制器,我该如何配置呢?
How do I configure this, considering This-Is-a-Page
might be a controller also?
推荐答案
如果您的控制器"路由和页面"路由(请参见下文)都使用相同的/something
,那么您必须执行以下规则:
If both your "controller" routes and "page" routes (see below) use the same /something
, then you're going to have to implement the following rules:
在路线顶部:
route. MapRoute(
"ControllerRoute"
"{controller}",
new { controller = "Home", action = "Index" }
new { controller = GetControllerNameRegex() }
);
route.MapRoute(
"PageRoute",
"{pageSlug}"
new { controller = "Page", action = "ShowPage" }
);
- 任何页面的名称都不能与使用中的任何控制器相匹配.
- 或者没有控制器具有与正在使用的任何页面相匹配的名称.
Since you can't really do the latter programmatically, but you can do the former programmatically, you can add a custom constraint to your controller routes, so that it will only hit if you happen to type the name of a controller:
private static string GetControllerNameRegex()
{
var controllerNamesRegex = new StringBuilder();
List<string> controllers = GetControllerNames();
controllers.ForEach(s =>
controllerNamesRegex.AppendFormat("{0}|", s));
return controllerNamesRegex.ToString().TrimEnd('|');
}
private static List<Type> GetSubClasses<T>()
{
return Assembly.GetCallingAssembly().GetTypes().Where(type =>
type.IsSubclassOf(typeof(T))).ToList();
}
public List<string> GetControllerNames()
{
List<string> controllerNames = new List<string>();
GetSubClasses<Controller>().ForEach(type => controllerNames.Add(type.Name));
return controllerNames;
}
注意事项:最好的方法是确保没有以控制器命名的页面,并且可以使用上述代码在运行时强制执行该操作.
NB: Best course would be to make sure not to have any pages named after your controller, and you could use the above code to enforce that at runtime.
这篇关于如何分隔路径相同但功能不同的路线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!