我正在尝试构建灵活的URL路由。
所以url就像这样
en-US/ctrl/act/1/2应该像这样做
ctrl/act/1/2并将文化设置为en-US。
现在,我已经通过定义如下两条路由实现了这一点:
routes.MapRoute(
"Ctrl",
"ctrl/{action}/{group}/{page}",
new { controller = "Home", action = "Index", group = 1, page = 1 },
new { group = @"\d+", page = @"\d+" }
);
routes.MapRoute("CtrlWithCulture",
"{culture}/ctrl/{action}/{group}/{page}",
new { culture = "", controller = "Home", action = "Index", group = 1, page = 1 },
new { culture = "[a-z]{2}-(?:[a-zA-Z]{2,4}-)*(?:[a-zA-Z]{2,4})", group = @"\d+", page = @"\d+" }
);我有一个基本控制器,它根据输入参数设置区域性。但我想在默认情况下为所有路由提供此功能,所以我尝试了类似这样的功能。
Global.asax.cs:
routes.MapRoute("RootWithCulture",
"{culture}/{*rest}",
new { controller = "Home", action = "Index", culture = "" },
new { culture = "[a-z]{2}-(?:[a-zA-Z]{2,4}-)*(?:[a-zA-Z]{2,4})" }
);
MyController.cs
public class MyController : Controller
{
...
protected override void OnActionExecuting(ActionExecutingContext context)
{
if (!String.IsNullOrEmpty(context.RouteData.Values["culture"].ToStringOrNull()))
{
this.SetCulture(String.IsNullOrEmpty(context.RouteData.Values["culture"])
context.RouteData.Values.Remove("culture");
// I'm stuck here!
// I want to try other routes and find and execute the right one...我不确定什么方法才是正确的……
发布于 2009-11-12 21:56:21
最后,我用一个定制的RoutingModule完成了这项工作,如下所示:
public class RewritingRoutingModule : UrlRoutingModule
{
protected string routeNameToRewrite = "rewrite";
public override void PostResolveRequestCache(HttpContextBase context)
{
RouteData routeData = this.RouteCollection.GetRouteData(context);
if (routeData != null)
{
if (routeData.Values.ContainsKey(routeNameToRewrite))
{
// take all route parameters before *rewrite
IEnumerable<KeyValuePair<string, object>> additionalData = routeData.Values.TakeWhile(item => item.Key != routeNameToRewrite);
// put route parameter names and values into HttpContextBase.Item collection
foreach (KeyValuePair<string, object> item in additionalData)
context.Items.Add(item.Key, item.Value);
// rewrite the route with *rewrite part only
context.RewritePath("~/" + (routeData.Values[routeNameToRewrite] != null ? routeData.Values[routeNameToRewrite].ToString() : ""));
}
}
base.PostResolveRequestCache(context);
}我在Global.asax的末尾放置了这样一条路由:
routes.MapRoute("RewritingRoute-Culture", "{culture}/{*rewrite}", new { }, new { culture = @"en-US|de-AT" });因此,如果匹配,它会将值附加到HttpContextBase.Items,然后使用controller etc找到另一个路由并执行该路由。
https://stackoverflow.com/questions/1306570
复制相似问题