Best way to format a query string in an asp.net mvc url?

北城余情 提交于 2019-12-12 13:24:26

问题


I've noticed that if you sent a query string routevalue through asp.net mvc you end up with all whitespaces urlencoded into "%20". What is the best way of overriding this formatting as I would like whitespace to be converted into the "+" sign?

I was thinking of perhaps using a custom Route object or a class that derives from IRouteHandler but would appreciate any advice you might have.


回答1:


You could try writing a custom Route:

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;
    }
}

And register it like this:

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


来源:https://stackoverflow.com/questions/2903325/best-way-to-format-a-query-string-in-an-asp-net-mvc-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!