【问题标题】:ASP.NET MVC Default URL ViewASP.NET MVC 默认 URL 视图
【发布时间】:2011-01-01 16:14:00
【问题描述】:

我正在尝试将我的 MVC 应用程序的默认 URL 设置为我的应用程序区域内的一个视图。该区域称为“Common”,控制器为“Home”,视图为“Index”。

我尝试将 web.config 的表单部分中的 defaultUrl 设置为“~/Common/Home/Index”,但没有成功。

我也尝试在 global.asax 中映射一条新路线,因此:

routes.MapRoute(
        "Area",
        "{area}/{controller}/{action}/{id}",
        new { area = "Common", controller = "Home", action = "Index", id = "" }
    );

再次,无济于事。

【问题讨论】:

  • 经过进一步调查,无论是否有您建议的更改,该请求似乎都被定向到正确的控制器(即 MyApp.Areas.Common.Controllers.HomeController)。但是,在这两种情况下,ViewEngine 只搜索 ~/Views/Home 和 ~/Views/Shared 文件夹,而不是从 ~/Areas/Common/Views/Home 和 ~/Areas/Common/Views/Shared 开始。奇怪的是,如果我创建一个带有 ActionLink 到同一控制器方法(即 Index())的页面,那么它就可以正常工作。嗯。
  • stackoverflow.com/questions/2140208/… 这可能会有所帮助。我有类似的问题。

标签: asp.net asp.net-mvc web-config asp.net-mvc-routing url-routing


【解决方案1】:

您列出的路线仅在他们明确输入 URL 时才有效:

yoursite.com/{area}/{controller}/{action}/{id}

那条路线的意思是:

如果我收到的请求在该区域中具有有效的{area}、有效的{controller},并且在该控制器中具有有效的{action},则将其路由到那里。

如果他们只是访问您的站点,您想要默认使用该控制器,yoursite.com

routes.MapRoute(
    "Area",
    "",
    new { area = "Common", controller = "Home", action = "Index" }
);

这就是说,如果他们不向http://yoursite.com 附加任何内容,则将其路由到以下操作:Common/Home/Index

另外,把它放在你的路由表的顶部。

确保您也让 MVC 知道注册您在应用程序中拥有的区域:

将以下内容放入Global.asax.cs 文件中的Application_Start 方法中:

AreaRegistration.RegisterAllAreas();

【讨论】:

  • 对我来说这是在根文件上搜索,而不是在该区域中。
【解决方案2】:

你要做的是:

  • 从 global.asax.cs 中删除默认路由

    //// default route map will be create under area
    //routes.MapRoute(
    //    name: "Default",
    //    url: "{controller}/{action}/{id}",
    //    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    //);
    
  • 更新公共区域中的 SecurityAreaRegistration.cs

  • 添加以下路由映射:

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

【讨论】:

    【解决方案3】:

    你所做的似乎是正确的。如果我不得不猜测,我会说这是由于您运行网站的方式而发生的。在 Visual Studio 中,如果您在按 F5 时选择了特定视图,该视图将作为起始 URL - 尝试选择项目,然后按 F5?

    【讨论】:

    • 恐怕这不是问题的原因。不过谢谢你的建议。
    【解决方案4】:

    在 Global.asax 删除.MapRoute

    让它看起来像

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

    然后在该区域的 yourareaAreaRegistration.cs 下(如果您通过 VS 添加区域,它就在那里)

    public override void RegisterArea(AreaRegistrationContext context)
    {
         //This is the key one         
         context.MapRoute("Root", "", new { controller = "Home", action = "Login" });
    
         //Add more MapRoutes if needed
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-14
      • 2021-12-18
      • 2021-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-19
      • 2010-11-01
      • 2013-01-31
      相关资源
      最近更新 更多