Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 649
Neilski Avatar asked Jan 17 '26 23:01

Neilski


1 Answers

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")));
like image 74
Jone Polvora Avatar answered Jan 20 '26 21:01

Jone Polvora