以下是家庭控制器中的代码:
public ActionResult Index()
{
return View();
}
public ActionResult AboutUs()
{
return View();
}
以下是我的RouteConfig.cs中的代码
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"AboutUsPage",
"about",
new { Controller = "Home", action = "AboutUs", });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
现在,如果我点击地址“ localhost:9731 / Home / AboutUs”,那么它将在Home Controller中点击我的AboutUs操作。同样,如果我命中了地址“ localhost:9731 / about”,那么它将通过RouteConfig.cs中的URL重写命中Home Controller中的AboutUs操作。
问题是当用户在地址栏中单击“ localhost:9731 / Home / AboutUs”时如何显示“ localhost:9731 / about”?请帮我。谢谢。
最佳答案
一种方法是将301永久重定向到新路由。因此,您可以拥有一个重定向控制器:
public class RedirectController : Controller
{
public ActionResult Index(string redirectToAction, string redirectToController)
{
return this.RedirectToActionPermanent(redirectToAction, redirectToController);
}
}
然后将您的旧路由配置为重定向到新路由:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"AboutUsPage",
"about",
new { controller = "Home", action = "AboutUs", });
routes.MapRoute(
name: "AboutUsLegacy",
url: "Home/AboutUs",
defaults: new {
controller = "Redirect",
action = "Index",
redirectToAction = "AboutUs",
redirectToController = "Home" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
在此示例中,我们在默认路由之前添加了新路由,它将侦听您要重定向的旧路由(
/Home/AboutUs
),然后将301重定向发送到/about