Reputation: 41
Following is the code in Home Controller :
public ActionResult Index()
{
return View();
}
public ActionResult AboutUs()
{
return View();
}
Following is code in my 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 }
);
}
Now If I hit the address "localhost:9731/Home/AboutUs" then It will Hit my AboutUs action in Home Controller. similarly If I hit the address "localhost:9731/about" then It will Hit my AboutUs action in Home Controller beacuse of URL rewriting in RouteConfig.cs.
Question is that How to display "localhost:9731/about" when User hit "localhost:9731/Home/AboutUs" in address bar??. Please help me. Thanks.
Upvotes: 2
Views: 13659
Reputation: 1039598
One way to achieve that would be to make 301 Permanent redirect to the new route. So you could have a redirect controller:
public class RedirectController : Controller
{
public ActionResult Index(string redirectToAction, string redirectToController)
{
return this.RedirectToActionPermanent(redirectToAction, redirectToController);
}
}
and then configure your legacy route to redirect to the new one:
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 }
);
}
In this example we have added a new route before the default one which will listen for the legacy route that you want to redirect (/Home/AboutUs
) and then it will issue the 301 redirect to /about
Upvotes: 3