【问题标题】:Route matching with GetVirtualPath与 GetVirtualPath 匹配的路由
【发布时间】:2010-10-21 13:16:26
【问题描述】:

我的应用程序中有以下路由...

public static void RegisterRoutes(RouteCollection routes)
{
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  routes.MapRoute(
    "Branding",
    "foo/bar.css",
    new { controller = "DynamicContent", action = "CSS" }
  );

  routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Account", action = "Index", id = UrlParameter.Optional }
  );
}

我正在使用Martijn Boland's paging mechanism,它最终会进行以下调用:

var virtualPathData = 
  RouteTable.Routes.GetVirtualPath(this.viewContext.RequestContext, pageLinkValueDictionary);

我已验证我在 RequestContext 中的控制器和操作是有效的。但是一旦进行了这个调用,virtualPathData 就会引用 foo/bar.css 的 URL。我已验证 URL 映射到正确的控制器/操作。如果我注释掉上面的路由保留默认值,virtualPathData 的 URL 对应于正确的控制器/动作。

我也尝试了以下行,结果相同。

//var virtualPathData = 
  RouteTable.Routes.GetVirtualPathForArea(this.viewContext.RequestContext, pageLinkValueDictionary);

谁能帮我弄清楚我做错了什么?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-2 routing paging


    【解决方案1】:

    不幸的是,我认为生成 URL 的逻辑不能很好地处理静态 URL。我相信您可以做的一件事是:

    routes.MapRoute(
        "Branding",
        "{controller}/bar.css",
        new { controller = "DynamicContent", action = "CSS" },
        new {controller="foo"}
      );
    

    试试看。

    【讨论】:

    • 谢谢菲尔,它比我的提议更有效并且更干净(回想起来很像双重否定) - 我很感激!
    【解决方案2】:

    我仍然不确定为什么我会看到上述行为,所以如果有人想加入他们的想法,请随意。

    也就是说,如果其他人遇到同样的问题,我可以通过反转路由顺序来克服它,首先添加更模糊的默认路由,并带有 NotEqual 约束,以确保根据需要命中 DynamicContent 路由。

    routes.MapRoute(
      "Default",
      "{controller}/{action}/{id}",
      new { controller = "Account", action = "Index", id = UrlParameter.Optional },
      new { controller = new NotEqual("DynamicContent") }
    );
    
    routes.MapRoute(
      "Branding",
      "foo/bar.css",
      new { controller = "DynamicContent", action = "CSS" }
    );
    

    对于那些想知道 NotEqual 是什么的人,我找到了 on a blog

    public class NotEqual : IRouteConstraint
    {
      private string _match = string.Empty;
    
      public NotEqual(string match)
      {
        _match = match;
      }
    
      public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
      {
        return String.Compare(values[parameterName].ToString(), _match, true) != 0; 
      }
    }
    

    我当然愿意听到更好的方法或为什么我的原始代码不能完全工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-01
      • 2014-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多