ASP.NET MVC重新映射Catch-All参数值并执行另一个有效路由

时间:2009-08-20 14:27:16

标签: asp.net-mvc

我正在尝试构建灵活的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...

我不确定这是什么方法......

1 个答案:

答案 0 :(得分:1)

最后,我使用了这样的自定义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,然后找到另一个带有控制器等的路由并执行该路径。