Stilgar
Stilgar

Reputation: 23551

How to create an ASP.NET route that redirects to a path that uses part of the route?

I want to create a route that redirects all requests matching certain pattern to a location built using parts of the pattern. I want to grab some segment in the URL and treat the rest like a path to an aspx page in Web Forms application. For example

RouteTable.Routes.MapPageRoute("SomeRouteName", "{something}/{*path}", "~/pages/{*path}/Default.aspx");

Where *path could be something contain "\". The query string should be preserved as a query string.

Is it possible to create souch a route?

Upvotes: 0

Views: 624

Answers (2)

Stilgar
Stilgar

Reputation: 23551

After looking at several ways to do this I ended up creating my own routing handler that is something like this:

public class SomethingRoutingHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        string something = (string)requestContext.RouteData.Values["something"];
        string path = (string)requestContext.RouteData.Values["path"];

        string virtualPath = "~/" + path + "Default.aspx";

        return BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof(Page)) as Page;
    }
}

I then use the RouteData in the pages to access something. I found these articles helpful:

http://msdn.microsoft.com/en-us/magazine/dd347546.aspx

http://www.xdevsoftware.com/blog/post/Default-Route-in-ASPNET-4-URL-Routing.aspx

Upvotes: 0

Jonathan Wood
Jonathan Wood

Reputation: 67195

I don't know of any way to do it that way.

The more standard way would be to set the target as "~/pages/default.aspx" and then have that page check for the {path} argument and display the corresponding data.

If you really want it in another path, then don't use a {} placeholder. Simply hard code that section of the path (both the source and target).

Upvotes: 1

Related Questions