14

routes.LowercaseUrls = true;在我的 MVC 4 应用程序中使用它,它运行良好。但是,参数也会小写,所以如果我有类似的路线

routes.MapRoute(
    name: "MyController",
    url: "foo/{hash}/{action}",
    defaults: new { controller = "MyController", action = "Details" }
);

生成的链接

@Html.ActionLink("my link", "Details", new { hash=ViewBag.MyHash })

URL 的 - 部分也将{hash}小写,例如,如果ViewBag.MyHash = "aX3F5U"生成的链接将/foo/ax3f5u不是/foo/aX3F5U

有没有办法强制 MVC 只小写控制器和动作部分?

对于旧版本的 MVC,要走的路似乎是实现的自定义子类Route,但是我不知道如何/在哪里实例化它,因为路由构造函数的签名MapRoute与我希望有成为一种更简单的方法。

4

4 回答 4

2

我认为具有自定义子类的解决方案Route将足够好且简单,但同时有点难看:)

您可以添加CustomRouteatRegisterRoute方法RouteConfig.cs。添加以下代码而不是routes.MapRoute

var route = new CustomRoute(new Route(
  url: "{controller}/{action}/{id}",
  defaults: new RouteValueDictionary() { 
    { "controller", "Home" }, 
    { "action", "Index" }, 
    { "id", UrlParameter.Optional }
  },
  routeHandler: new MvcRouteHandler()
));
routes.Add(route);

具体的实现CustomRoute可能如下所示:

public class CustomRoute : RouteBase
{
  private readonly RouteBase route;

  public CustomRoute(RouteBase route)
  {
    this.route = route;
  }

  public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
  {
    values = new RouteValueDictionary(values.Select(v =>
    {
      return v.Key.Equals("action") || v.Key.Equals("controller")
        ? new KeyValuePair<String, Object>(v.Key, (v.Value as String).ToLower())
        : v;
    }).ToDictionary(v => v.Key, v => v.Value));

    return route.GetVirtualPath(requestContext, values);
  }

  public override RouteData GetRouteData(HttpContextBase httpContext)
  {
    return route.GetRouteData(httpContext);
  }
}

但是,这不是最佳实现。一个完整的示例可以使用扩展RouteCollection和自定义Route子项的组合,以使其尽可能接近原始routes.MapRoute(...)语法:

小写路由类:

public class LowercaseRoute : Route
{
    public LowercaseRoute(string url, IRouteHandler routeHandler) : base(url, routeHandler) { }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
        values = new RouteValueDictionary(values.Select(v =>
        {
            return v.Key.Equals("action") || v.Key.Equals("controller")
              ? new KeyValuePair<String, Object>(v.Key, (v.Value as String).ToLower())
              : v;
        }).ToDictionary(v => v.Key, v => v.Value));

        return base.GetVirtualPath(requestContext, values);
    }
}

RouteCollectionExtensions 类:

public static class RouteCollectionExtensions
{
    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#", Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapLowercaseRoute(this RouteCollection routes, string name, string url)
    {
        return MapLowercaseRoute(routes, name, url, null /* defaults */, (object)null /* constraints */);
    }

    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#", Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapLowercaseRoute(this RouteCollection routes, string name, string url, object defaults)
    {
        return MapLowercaseRoute(routes, name, url, defaults, (object)null /* constraints */);
    }

    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#", Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapLowercaseRoute(this RouteCollection routes, string name, string url, object defaults, object constraints)
    {
        return MapLowercaseRoute(routes, name, url, defaults, constraints, null /* namespaces */);
    }

    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#", Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapLowercaseRoute(this RouteCollection routes, string name, string url, string[] namespaces)
    {
        return MapLowercaseRoute(routes, name, url, null /* defaults */, null /* constraints */, namespaces);
    }

    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#", Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapLowercaseRoute(this RouteCollection routes, string name, string url, object defaults, string[] namespaces)
    {
        return MapLowercaseRoute(routes, name, url, defaults, null /* constraints */, namespaces);
    }

    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#", Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapLowercaseRoute(this RouteCollection routes, string name, string url, object defaults, object constraints, string[] namespaces)
    {
        if (routes == null)
        {
            throw new ArgumentNullException("routes");
        }
        if (url == null)
        {
            throw new ArgumentNullException("url");
        }

        Route route = new LowercaseRoute(url, new MvcRouteHandler())
        {
            Defaults = CreateRouteValueDictionary(defaults),
            Constraints = CreateRouteValueDictionary(constraints),
            DataTokens = new RouteValueDictionary()
        };

        if ((namespaces != null) && (namespaces.Length > 0))
        {
            route.DataTokens["Namespaces"] = namespaces;
        }

        routes.Add(name, route);

        return route;
    }

    private static RouteValueDictionary CreateRouteValueDictionary(object values)
    {
        var dictionary = values as IDictionary<string, object>;
        if (dictionary != null)
        {
            return new RouteValueDictionary(dictionary);
        }

        return new RouteValueDictionary(values);
    }
}

您现在可以使用MapLowercaseRoute代替MapRoute,所以

routes.MapRoute(
    name: "MyController",
    url: "foo/{hash}/{action}",
    defaults: new { controller = "MyController", action = "Details" }
);

简单地变成

routes.MapLowercaseRoute(
    name: "MyController",
    url: "foo/{hash}/{action}",
    defaults: new { controller = "MyController", action = "Details" }
);

暴露期望的行为。

于 2013-03-16T22:24:49.203 回答
2

这是一种简单的方法,

public class MyRoute : Route
{
    public MyRoute(string url, object defaults): base(url, new RouteValueDictionary(defaults), new MvcRouteHandler())
    { 
    }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
        if (values["action"] != null)
            values["action"] = values["action"].ToString().ToLowerInvariant();
        if (values["controller"] != null)
            values["controller"] = values["controller"].ToString().ToLowerInvariant();
        return base.GetVirtualPath(requestContext, values);
    }
}

routes.Add("Default",new MyRoute("{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = MyUrlParameter.Optional }));

有关详细信息,请参阅此博客文章

于 2013-03-17T11:52:45.207 回答
0

如果您查看私有RouteCollection.NormalizeVirtualPath方法,您会发现它只是使用virtualPath.ToLowerInvariant(). 所以没有办法处理它。即使您创建自己的路线,它也会小写。

但是您可以做的是在 '#' 符号 ie 之后添加哈希"foo/{action}/#{hash}"。我没试过,但它应该工作。只看NormalizeVirtualPath执行。

于 2013-03-17T09:38:10.440 回答
-1

就像 1.2.3 一样简单,

看这个例子

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

通过 Nuget 下载和安装很简单,我使用它。 PM> Install-Package LowercaseRoutesMVC

http://lowercaseroutesmvc.codeplex.com/

于 2013-03-17T06:08:07.547 回答