ASP.NET MVC4 with webforms Default.aspx as the sta

2019-04-08 14:46发布

问题:

I had an ASP.NET MVC4 app with the following routing defined in the Global.asax.cs. The app's start page is Index.cshtml view that is returned from the action method Index() of the Home controller. I then added a legacy ASP.NET WebForms app that had Default.aspx as the start page. How can I make this Default.aspx page as the start page of this integrated MVC+WebForms app:

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

            routes.MapRoute(
                "Default",
                "{controller}.mvc/{action}/{id}",
                new { action = "Index", id = "" }
              );


              routes.MapRoute(
              "Root",
              "",
              new { controller = "Home", action = "Index", id = "" }
            );


        }

回答1:

Try the following in your Global.asax:

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

    // Web Forms default
    routes.MapPageRoute(
        "WebFormDefault",
        "",
        "~/default.aspx"
    );

    // MVC default
    routes.MapRoute(
        "Default",                          // Route name
        "{controller}/{action}/{id}",       // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }  // parameter default
    );
}

Also I don't think you'll need the .mvc portion of the Default route.



回答2:

Removing 'controller = "Home"' from defaults parameter worked great for me. I found that solution here: https://stackoverflow.com/a/21213711/9793076.

Change the defaults parameter from:

new { controller = "Home", action = "Index", id = UrlParameter.Optional }

to:

new { action = "Index", id = UrlParameter.Optional }

The current solution breaks the routing of MVC links as @nam said.