【问题标题】:C# - How to Rewrite a URL in MVC3C# - 如何在 MVC3 中重写 URL
【发布时间】:2026-02-04 08:25:01
【问题描述】:

我有一个这样的网址: http://website.com/Profile/Member/34

我需要这个 URL 像这样运行: http://website.com/Profile/John

将 John 作为用户 id=34 的个人资料名称。

谁能给我指路吗?

【问题讨论】:

  • 您是否尝试更改 URL,以便如果有人导航到 http://website.com/Profile/Member/34,它将在他们的浏览器中显示为 http://website.com/Profile/John?或者您是在问如何执行查找,以便用户可以在浏览器中输入http://website.com/Profile/John,它会找到用户 ID = 34 的成员?
  • 是的,Dommer,我想如果有人导航到 Profile/Member/34 它显示 Profile/John... 不是控制器路由的问题,我需要重写 URL...

标签: asp.net-mvc-3 url-rewriting


【解决方案1】:

在 global.asx 中你需要添加一个新的路由。

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapRoute(
            "Member", // Route name
            "Profile/{member}", // URL with member 
            new { controller = "YourController", action = "Profile"}
        );

    }

您仍需要实现处理基于 {member} 查找个人资料的操作。

【讨论】:

    【解决方案2】:

    您必须在 global.ascx.cs 中添加一个自定义路由,用于重定向到好的控制器。但我猜“John”不是唯一值,因此您必须将 id 保留在 Url 中,或者如果 John 是用户名并且是唯一的,您可以使用此 url:

    routes.MapRoute("Member", "Profile/{member}", new { controller = "Member", action = "Profile"});
    

    然后在您的控制器中,您将拥有:

    public ActionResult Profile(string username){
        //fetch from the db
    }
    

    如果“John”不是唯一值,我建议您使用:

    routes.MapRoute("Member", "Profile/{id}/{member}", new { controller = "Member", action = "Profile"});
    

    所以你的 Url 看起来像 http://website.com/Profile/John/34 并且你是控制器:

     public ActionResult Profile(int id){
            //fetch from the db
        }
    

    如果您需要更多帮助,请告诉我!

    【讨论】:

    • 嗨 VinnyG,实际上我需要将控制器保留为配置文件,将我的操作保留为成员,并按用户 ID 进行搜索,但是当它显示在 URL 中时,我需要重写控制器/用户名