ASP.NET MVC路由:如何定义自定义路由

Meg*_*att 5 asp.net-mvc routes custom-routes

我已经在网上寻找这个问题的答案,但老实说,我似乎找不到MVC路线的好参考.

我的User对象有一个UserController.可以在用户上编辑,保存,查看等,因此我在该控制器中有操作来处理每个操作.这一切都很简单.但我最近创建了一个新的UserProfile对象,人们也可以编辑,查看等.而不是仅为UserProfile创建一个全新的控制器,我想利用现有的UserController.因此,要查看用户的个人资料,我希望网址为:

http://www.example.com/User/Profile/{userProfileID}
Run Code Online (Sandbox Code Playgroud)

要编辑,我希望URL为:

http://www.example.com/User/Profile/Edit/{userProfileID}
Run Code Online (Sandbox Code Playgroud)

UserController中的每个操作都将返回不同的视图页面.

我如何定义处理这种结构的路线?非常感谢.

Dis*_*ile 11

在RegisterRoutes()方法的Global.asax文件中,执行以下操作:

routes.MapRoute(
    "ProfileRoute",
    "User/Profile/{action}/{userProfileID}",
    new { controller = "User", action = "Index" });
Run Code Online (Sandbox Code Playgroud)

正如评论所指出的......这必须在默认路线之前.

  • 此外,作为一个FYI,因为它抓住了我,它必须在默认路线之前声明 (3认同)