我们如何在 ASP.NET MVC 中为整个区域设置授权? [英] How can we set authorization for a whole area in ASP.NET MVC?

查看:27
本文介绍了我们如何在 ASP.NET MVC 中为整个区域设置授权?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个管理区域,我只想让管理员进入该区域.我考虑将 Authorized 属性添加到管理区域中的每个控制器.难道没有优雅的解决方案,还是框架本身没有这个功能?

I've an Admin area and I want only Admins to enter the area. I considered adding the Authorized attribute to every controller in the Admin area. Isn't there an elegant solution or is this feature not there in the framework itself?

对不起,我应该之前提到过这一点.我正在使用从 AuthorizeAttribute 派生的自定义 AuthorizedAttribute.

I'm sorry, I should to have mentioned this before. I'm using a custom AuthorizedAttribute derived from AuthorizeAttribute.

推荐答案

基于 Web.config 的安全性应该几乎从不在 MVC 应用程序中使用.这样做的原因是多个 URL 可能会访问一个控制器,并且将这些检查放在 Web.config 中总是会遗漏一些东西.请记住 - 控制器与区域无关,路由与区域相关联.如果没有冲突,MVC 控制器工厂将很乐意为来自 Areas/文件夹的控制器提供非区域请求.

Web.config-based security should almost never be used in an MVC application. The reason for this is that multiple URLs can potentially hit a controller, and putting these checks in Web.config invariably misses something. Remember - controllers are not associated with areas, routes are associated with areas. The MVC controller factory will happily serve controllers from the Areas/ folder for non-area requests if there's no conflict.

例如,使用默认的项目结构,添加一个带有 AdminDefaultController 的管理区域,您可以通过/Admin/AdminDefault/Index /AdminDefault/Index 来访问该控制器.

For example, using the default project structure, adding an Admin area with an AdminDefaultController, you can hit this controller via /Admin/AdminDefault/Index and /AdminDefault/Index.

唯一支持的解决方案是将您的属性放在控制器基类上,并确保区域内的每个控制器都继承该基类.

The only supported solution is to put your attribute on a controller base class and to ensure that each controller within the area subclasses that base class.

这篇关于我们如何在 ASP.NET MVC 中为整个区域设置授权?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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