如何使/ Home / Index重定向到/

时间:2014-08-17 21:43:15

标签: c# asp.net-mvc routes

鉴于默认路由,以下任一URL都将导航到Index控制器的Home方法:

 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 }
);

2 个答案:

答案 0 :(得分:3)

在您的路线文件中,添加以下内容:

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

在你的HomeController中

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

答案 1 :(得分:0)

在HomeController的Index()方法中,只需添加:

Redirect("~/");
相关问题