C# 如何在MVC中更改URL?

C# 如何在MVC中更改URL?,c#,url,model-view-controller,rewriting,C#,Url,Model View Controller,Rewriting,以下是Home Controller中的代码: public ActionResult Index() { return View(); } public ActionResult AboutUs() { return View(); } 以下是我的RouteConfig.cs中的代码 public static void RegisterRoutes(RouteC

以下是Home Controller中的代码:

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控制器中的AboutUs操作。类似地,如果我点击地址“localhost:9731/about”,那么它将点击Home Controller中的AboutUs操作,因为在RouteConfig.cs中重写了URL


问题是,当用户在地址栏中点击“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

,谢谢@达林·迪米特罗夫:这对我很有效。我们可以为www.xyz.com到xyz.com实现同样的功能吗?当然,实现这一功能的一种方法是使用一个全局的
应用程序\u BeginRequest
ASP.NET事件来处理这个问题:我想你有一个语法错误
action=“AboutUs”,
你需要去掉那个逗号