使用webforms和MVC路由到项目的aspx页面

时间:2014-05-20 14:18:58

标签: asp.net asp.net-mvc asp.net-mvc-routing

我已经将MVC添加到我正在努力的现有webforms项目中,因为我希望慢慢迁移项目,但是,在转换期间,我需要能够访问两者,但默认为aspx页面。

在注册路由时,我目前已经准备好了:

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

        routes.MapPageRoute("Backup", "{*anything}", "~/Default.aspx");

        routes.MapRoute(
            "MVC", 
            "{controller}/{action}/{id}", 
            new { controller = "Test", action = "Index", id = 1 }
        );
    }

然而,当我设置这样的设置时,即使我输入一个我知道的URL指向控制器/动作组合(例如,从最后一行开始的测试和索引),它仍然会将用户重定向到Default.aspx页面。

我已尝试将此更改为以下内容:

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

        routes.MapRoute(
            "MVC",
            "{controller}/{action}/{id}",
            new { controller = "Test", action = "Index", id = 1 }
        );

        routes.MapPageRoute("Backup", "{*anything}", "~/Default.aspx");
    }

在这里,用户可以指定页面或指定控制器/操作,但如果它们不包含任何控制器/ aspx页面,则默认为默认的MVC路由,而我需要它默认为webform Default.aspx

如何解决这种情况,以便如果没有指定页面/控制器,它会指向〜/ Default.aspx,如果指定了控制器,它会指向该控制器?

1 个答案:

答案 0 :(得分:4)

我尝试过你的场景,我有一个现有的Web表单应用程序,并添加了mvc。基本上我遇到过两种解决方案。

首先:您可以忽略添加routes.MapPageRoute到路由配置;这就是我所做的

public static class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.EnableFriendlyUrls();

            routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

请注意 我已将默认值中的控制器值排除在外。现在,即使存在匹配,并且如果该名称不存在控制器,则该请求将回退到寻找aspx页面的常规ASP.Net管道。使用此方法,您可以请求http://localhost:62871/http://localhost:62871/Home/Indexhttp://localhost:62871/Home/http://localhost:62871/About.aspx

等网址

第二::在此方法中,您可以在 Areas 文件夹下为新的基于MVC的工作创建区域,并保留App_Start中的RouteConfig 设置为默认值,以便它看起来像跟随。

public static class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.EnableFriendlyUrls();
        }
    }

然后在您的区域注册类中定义路由,如下例所示。

public class AdminAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "Admin";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "Admin_default",
                "{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }

希望有所帮助。感谢。

相关问题