How to change URL in MVC c#?
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
Admin
Updated on June 04, 2022Comments
-
Admin almost 2 years
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.
-
Admin over 7 yearsThanks. @Darin Dimitrov It works for me. can we implement same for www.xyz.com to xyz.com??
-
Darin Dimitrov over 7 yearsSure, one way to achieve that is to have a global
Application_BeginRequest
ASP.NET event that will take care of this: stackoverflow.com/a/3197446/29407