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

ⅰ亾dé卋堺 提交于 2019-12-13 14:15:54

问题


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.


回答1:


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")));


来源:https://stackoverflow.com/questions/21887900/how-to-route-web-pages-on-a-mixed-mvc-and-web-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!