views:

48

answers:

1

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.

+2  A: 

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()
    )
);
Darin Dimitrov
Thanks Darin. This is perfect.
Stuart