C# - How to Rewrite a URL in MVC3

﹥>﹥吖頭↗ 提交于 2019-12-12 04:37:55

问题


I have an URL like this: http://website.com/Profile/Member/34

I need this URL runs like this: http://website.com/Profile/John

Given John as profile name for the user id=34.

Can anyone give me directions to do that?


回答1:


In global.asx you need to add a new route.

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

    }

You will still need to implement the action that handles looking up the profile based on {member}.




回答2:


You have to add a custom route in the global.ascx.cs that will be used to redirect to the good controller. But I guess that "John" is not a unique value so you will have to keep the id in the Url, or if John is the username and is unique you can go with this url:

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

Then in your controller you will have :

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

If "John" is not a unique value I suggest you use :

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

So your Url will look like http://website.com/Profile/John/34 and youre controller :

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

Let me know if you need more help!



来源:https://stackoverflow.com/questions/7602572/c-sharp-how-to-rewrite-a-url-in-mvc3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!