I would like to use Response.RedirectToRoute to redirect to "products/tools.aspx".
Response.RedirectToRoute(new { cat1 = "tools" }); redirects to "products/tools/steel.aspx"
Response.RedirectToRoute(new { cat1 = "tools", cat2 = "" }); redirects to "products/tools.aspx?cat2=steel"
Response.RedirectToRoute("route2", new { cat1 = "tools" }); redirects to "products/tools.aspx?cat2=steel"
Basically it seems the existing route values are being used in the redirect instead of what I specify. This behaviour can make sense, since it makes it easy to redirect to a url with only one route value different. But why when I specify it to be empty or specify
what route to use does it add the existing value as a querystring argument, and is there a way around this?
mcm
Member
77 Points
37 Posts
How to clear existing route value when using Response.RedirectToRoute
Dec 09, 2010 03:13 AM|LINK
If I have the following routes:
RouteTable.Routes.MapPageRoute("route1", "products/{cat1}/{cat2}.aspx", "categories.aspx");
RouteTable.Routes.MapPageRoute("route2", "products/{cat1}.aspx", "categories.aspx");
And am at this url:
products/door/steel.aspx
I would like to use Response.RedirectToRoute to redirect to "products/tools.aspx".
Response.RedirectToRoute(new { cat1 = "tools" }); redirects to "products/tools/steel.aspx"
Response.RedirectToRoute(new { cat1 = "tools", cat2 = "" }); redirects to "products/tools.aspx?cat2=steel"
Response.RedirectToRoute("route2", new { cat1 = "tools" }); redirects to "products/tools.aspx?cat2=steel"
Basically it seems the existing route values are being used in the redirect instead of what I specify. This behaviour can make sense, since it makes it easy to redirect to a url with only one route value different. But why when I specify it to be empty or specify what route to use does it add the existing value as a querystring argument, and is there a way around this?
mcm
Member
77 Points
37 Posts
Re: How to clear existing route value when using Response.RedirectToRoute
Dec 09, 2010 07:44 PM|LINK
One workaround I found at StackOverlow is to use this extension method:
public static void RedirectToRoute(this HttpResponse response, object routeValues, bool useExistingValues)
{
RequestContext context = useExistingValues ? HttpContext.Current.Request.RequestContext : null;
VirtualPathData path = RouteTable.Routes.GetVirtualPath(context, new RouteValueDictionary(routeValues));
response.Redirect(path.VirtualPath);
}
So calling this now works as desired:
Response.RedirectToRoute(new { cat1 = "tools" }, false) redirects to "products/tools.aspx"