在ASP.NET MVC URL中格式化查询字符串的最佳方法是什么?

3

我注意到,如果你通过Asp.net MVC发送一个查询字符串路由值,所有的空格都会被编码成“%20”。有没有什么好方法来覆盖这种格式,使空格转换为“+”符号呢?

我考虑过使用自定义路由对象或从IRouteHandler派生的类,但我很感激你可能提供的任何建议。

1个回答

3

您可以尝试编写自定义路由:

public class CustomRoute : Route
{
    public CustomRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler) 
        : base(url, defaults, routeHandler)
    { }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
        var path = base.GetVirtualPath(requestContext, values);
        if (path != null)
        {
            path.VirtualPath = path.VirtualPath.Replace("%20", "+");
        }
        return path;
    }
}

并且像这样进行注册:

routes.Add(
    new CustomRoute(
        "{controller}/{action}/{id}",
        new RouteValueDictionary(new { 
            controller = "Home", 
            action = "Index", 
            id = UrlParameter.Optional 
        }),
        new MvcRouteHandler()
    )
);

谢谢Darin。这太完美了。 - Stuart

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接