Search code examples
asp.netasp.net-routing

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?


Solution

  • 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