How to authorize a set of controllers without placing the annotation on each one?

若如初见. 提交于 2019-11-30 19:55:44

You can initialize those controllers derived from your base controller. namely put your attribute on a controller base class and to ensure that each controller within derived from base class.

[Authorize(Role="Class A")]
public class CustomBaseController : Controller{}

public class AController: CustomBaseController{}

public class BController: CustomBaseController{}

Yes there is a way, make all those A-class controller derived from one base controller and place on it the AuthorizeAttribute:

[Authorize(Role="Class A")]
public class AController : Controller 
{
    ...
} 

public class AFirstController : AController // Gets it's parent attribute
{
    ...
} 

public class ASecondController : AController // Gets it's parent attribute
{
    ...
} 
Romias

2 or 3 responses here explained how you can do it... but you can also use Fluent Security to handle all controllers + Actions setup in one file. Some of the benefits (from their website):

Code based configuration

No attributes or xml cluttering up your code.

Low imprint

Fluent Security won't spread like wildfire in your application. Your configuration can be kept in a single file.

You can inherit from a base controller, such as

[Authorize(Role = "Class A")]
public class ClassARequiredController : Controller {}

Otherwise you'd be looking at a global filter, and by your question I assume you have multiple roles and sets so I don't think global filters are for you.

Set the attribute on a Base Class and inherit, creating the hierarchy that best fits your scenario...

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