ASP.NET MVC3 将各个子文件夹路由到同一控制器
我正在尝试将我的 MVC 项目设置为具有 URL,以便我可以访问:
/群组/
/群组/注册
/群组/随便
但在我的控制器中,我还可以将某些操作标记为仅管理员,以便可以在以下位置访问它们:
/管理/组/删除/{id}
我想保留一个 GroupController
,并执行以下操作:
public class GroupController : Controller
{
public ActionResult Index(){
return View();
}
[AdminAction]
public ActionResult Delete(int id){
...
return View();
}
}
允许:
/Groups 是有效的 URL。
/Admin/Groups 是一个有效的 URL(但可能会调用除索引之外的其他操作)
/Admin/Groups/Delete/{id} 是一个有效的 URL(仅发布,无论如何)
/Groups/Delete 是无效网址。
我意识到这可能是一个相当广泛的问题,但我是 MVC 的新手,我不太确定从哪里开始寻找,所以如果您能指出我正确的方向,我将不胜感激。
I'm trying to set up my MVC project to have URLs so that I can go to:
/Groups/
/Groups/Register
/Groups/Whatever
But in my controller, I can also flag some actions as admin only, so that they are accessed at:
/Admin/Groups/Delete/{id}
I would like to keep one GroupController
, and have actions so that:
public class GroupController : Controller
{
public ActionResult Index(){
return View();
}
[AdminAction]
public ActionResult Delete(int id){
...
return View();
}
}
Allows:
/Groups is a valid URL.
/Admin/Groups is a valid URL (but would call some other action besides Index - maybe)
/Admin/Groups/Delete/{id} is a valid URL (post only, whatever)
/Groups/Delete is an INVALID url.
I realize this is probably a pretty broad question, but I'm new to MVC and I'm not really sure where to start looking, so if you could just point me in the right direction that would be hugely appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如我们在下面的评论中讨论的,虽然可以使用我下面的原始答案来实现您请求的路由解决方案,但更好的解决方案是使用 Areas,建立一个
Admin
区域,并在中创建控制器您的管理区域可以处理不同对象(例如组、用户等)的管理任务。这使您可以更轻松地设置受限制的管理功能,并且既是更好的设计,也是更好的安全模型。原始答案
您想要的可以通过使用以下路线来完成:
但是,正如 Akos 在评论中所说,将管理功能分离到不同的控制器中是一个更好的设计。虽然这是可能的,但我建议不要使用这种设计。
更新
如果请求管理员操作,可以在默认路由上使用
RouteConstraint
使其失败。默认路由将如下所示:RouteConstraint 将如下所示:
As we discussed in the comments below, while it is possible to use my original answer below to achieve the routing solution you requested, a better solution is to use Areas, establish an
Admin
area, and create controllers in your Admin area to handle the administrative tasks for different objects, such as Group, User, etc. This allows you to set up restricted administrative functions more easily, and is both a better design and a better security model.ORIGINAL ANSWER
What you want can be accomplished by using the following routes:
However, as Akos said in the comments, it is a much better design to separate the administrative functions into a different controller. While this is possible, I would recommend against using this design.
UPDATE
It is possible to use a
RouteConstraint
on your Default route to make it fail if Admin actions are requested. The Default route would look like this:The RouteConstraint would look like this: