ASP.NET MVC 路由:如何定义自定义路由 [英] ASP.NET MVC Routes: How to define custom route

查看:28
本文介绍了ASP.NET MVC 路由:如何定义自定义路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've looked online for an answer to this question, but I honestly can't seem to find a good reference for MVC routes.

我的 User 对象有一个 UserController.可以对用户进行编辑、保存、查看等操作,因此我在该控制器中有操作来处理每个操作.这一切都很简单.但我最近创建了一个新的 UserProfile 对象,用户还可以对其进行编辑、查看等.与其为 UserProfile 创建一个全新的控制器,我想利用现有的 UserController.因此,要查看用户的个人资料,我希望 URL 为:

I have a UserController for my User objects. One can Edit, Save, View, etc. on the User, so I have actions in that controller to handle each of those. That's all pretty straightforward. But I've recently created a new UserProfile object that one can also edit, view, etc. Rather than create an entirely new controller just for the UserProfile, I'd like to make use of the existing UserController. So to view a user's profile, I'd like the URL to be:

http://www.example.com/User/Profile/{userProfileID}

要编辑,我希望 URL 为:

And to edit, I'd like the URL to be:

http://www.example.com/User/Profile/Edit/{userProfileID}

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

Each of these actions in the UserController will return a different view page.

我将如何定义路由来处理这个结构?非常感谢.

How would I go about defining routes to handle this structure? Thanks very much.

推荐答案

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

In your Global.asax file in the RegisterRoutes() method do the following:

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

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

As pointed out by the comments...this must come BEFORE the Default route.

这篇关于ASP.NET MVC 路由:如何定义自定义路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆