给定默认路由,以下任一 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/