问题
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