How to route web pages on a mixed MVC and Web Forms

asp.net-mvc, asp.net-mvc-4, asp.net-mvc-routing

Solution

Just as a starting point, we can add specific routes for webforms pages in App_Start/RouteConfig.cs:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        //specific page route
        routes.MapPageRoute("forms", "forms", "~/Webforms/RootForm.aspx");

        //specific pattern to a directory
        routes.MapPageRoute("webformsmap", "{page}.aspx", "~/Webforms/{page}.aspx");


        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

EDIT

After some research, I've found exactly what you're looking for. I've create a useful custom IRouteHandler to achieve a better funcionality. This way you can map an entire directory of Webforms *.aspx pages to a single route. Check it out:

public class DirectoryRouteHandler : IRouteHandler
{
    private readonly string _virtualDir;

    public DirectoryRouteHandler(string virtualDir)
    {
        _virtualDir = virtualDir;
    }

    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        var routeValues = requestContext.RouteData.Values;

        if (!routeValues.ContainsKey("page")) return null;

        var page = routeValues["page"].ToString();
        if (!page.EndsWith(".aspx"))
            page += ".aspx";
        var pageVirtualPath = string.Format("{0}/{1}", _virtualDir, page);

        return new PageRouteHandler(pageVirtualPath, true).GetHttpHandler(requestContext);
    }
}

By using DirectoryRouteHandler, you can pretty achieve your goal.

url "~/somepage.aspx" will be mapped to "~/WebForms/somepage.aspx"

routes.Add("rootforms", new Route("{page}.aspx", 
    new DirectoryRouteHandler(virtualDir: "~/WebForms")));

url "~/forms/somepage" will be mapped to "~/WebForms/somepage.aspx"

routes.Add("webforms", new Route("forms/{page}", 
    new DirectoryRouteHandler(virtualDir: "~/WebForms")));

Problem

I have created a mixed MVC and Web Forms web site - very easy to do with the later Visual Studio 2013 tooling. All works well and I can navigate to both MVC and Web Forms pages correctly. What I would like to do however, is to put all of my Web Form pages in a specific sub-directory and then route to them without using the sub-directory. ``` / + Content + Controllers + Models + Scripts + Views + WebPages + Default.aspx + MyWebForm.aspx ``` So I would like to be able to access: ``` /WebPages/Default.aspx as /Default.aspx or even just / /WebPages/MyWebForm.aspx as /MyWebForm.aspx ``` Is this possible? Any advice would be appreciated.

Original source