在Asp.Net MVC中设置"Homepage"

Nik*_*nte 104 c# asp.net-mvc asp.net-mvc-routing

在asp.net MVC中,"主页"(即击中www.foo.com时显示的路线)设置为Home/Index.

  • 这个值存储在哪里?
  • 如何更改"主页"?
  • 是否有比在家庭控制器的Index操作中使用RedirectToRoute()更优雅的东西?

我尝试在我的项目中使用Home/Index进行grepping,找不到引用,也无法在IIS(6)中看到任何内容.我查看了root中的default.aspx页面,但这似乎没有做任何相关的事情.

谢谢

Mic*_*tum 149

看看Default.aspx/Default.aspx.cs和Global.asax.cs

您可以设置默认路由:

        routes.MapRoute(
            "Default", // Route name
            "",        // URL with parameters
            new { controller = "Home", action = "Index"}  // Parameter defaults
        );
Run Code Online (Sandbox Code Playgroud)

只需将控制器/操作名称更改为所需的默认值即可.这应该是路由表中的最后一条路由.

  • 在MVC 4中,这可以在App_Start/RouteConfig.cs中完成 (94认同)
  • @NikolaiDante你应该把这个评论作为答案,因为我几乎错过了它,它比这个答案更快.:) 谢谢 (6认同)
  • 在MVC 5.如果您有表单登录,当您在主页上单击登录时,它仍将重定向到Home控制器,而不是路由中指定的自定义控制器.注册动作也会做类似的事情.因此,除了更改routeconfig之外,还需要更改调用RedirectionToAction("Index","Home")的一些代码,并将其替换为您自己的控制器和操作名称. (3认同)

JTW*_*JTW 17

ASP.NET核心

路由ConfigureStartup类的方法中配置.要设置"主页",只需添加以下内容即可.当用户导航到您网站的基本URL时,这将导致用户被路由到MapRoute方法中定义的控制器和操作,即,yoursite.com将用户路由到yoursite.com/foo/index:

app.UseMvc(routes =>
{
   routes.MapRoute(
   name: "default",
   template: "{controller=FooController}/{action=Index}/{id?}");
});
Run Code Online (Sandbox Code Playgroud)

Pre-ASP.NET核心

使用位于App_Start/RouteConfig.cs(MVC 3和4)或Global.asax.cs(MVC 1和2)中的RegisterRoutes方法,如下所示.如果用户导航到您站点的基本URL,这将导致用户被路由到MapRoute方法中定义的控制器和操作,即,yoursite.com将用户路由到yoursite.com/foo/index:

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

    // Here I have created a custom "Default" route that will route users to the "YourAction" method within the "FooController" controller.
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "FooController", action = "Index", id = UrlParameter.Optional }
    );
}
Run Code Online (Sandbox Code Playgroud)


小智 5

步骤 1:单击解决方案中的 Global.asax 文件。

第 2 步:然后转到定义

RouteConfig.RegisterRoutes(RouteTable.Routes);

步骤 3:更改控制器名称和视图名称

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

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