c# - 如何使/首页/索引重定向到/

标签 c# asp.net-mvc routes

给定默认路由,以下任一 URL 将导航到 Home Controller 的 Index 方法:

 1. http://localhost
 2. http://localhost/Home/Index

我想这样做,以便当用户导航到 localhost/Home/Index 时,他们将被重定向到 localhost 未找到的结果。 `

我的目标是在不删除默认路由的情况下禁用 Home/Index 地址(因为它在其他地方很有用。

我想实现这一点,因为我在我的 JS 中有一些硬编码的相对 URL,只有当它们相对于 localhost 时才有效。

顺便说一下,默认路由是这样的:

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

最佳答案

在你的路由文件中,添加:

 routes.MapRoute(
         name: "HomeRedirect",
         url: "Home/Index",
         defaults: new { controller = "Home", action = "Index", redirect = true }
 );

在你的家庭 Controller 中

   public ActionResult Index(bool? redirect)
    {
        if (redirect.HasValue && redirect.Value)
            return RedirectToActionPermanent("Index", new { redirect = null as object });
        return View();
    }

关于c# - 如何使/首页/索引重定向到/,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25353924/

相关文章:

c# - 如何从Web服务生成的客户端应用程序中引用xml文件

c# - 在资源受限的移动设备中加密文件

c# - 当它不在模型中时如何将附加值传递给 Controller ​​?

asp.net-mvc - 自定义 EditorFor Template 和 htmlAttributes

c# - 导出到 excel 的 RadGrid telerik 问题

c# - AvalonDock 2.0 : adding LayoutDocument not working after Deserialize layout

asp.net - 如何使用 ASP.Net/MVC 5/EF 编写拍卖网站代码

c# - 从 MVC 路由处理程序返回 404

ruby-on-rails - Rails - 使用/自定义 URL : '/dashboard' 指定根路径

laravel - 语法错误,意外的 'Route'(T_STRING)