如何为某些特定的控制器添加自定义AuthorizeAttribute使用MVC上的代码
本文关键字:AuthorizeAttribute 自定义 使用 MVC 代码 添加 控制器 | 更新日期: 2023-09-27 18:28:38
一般情况下,我们只是将属性放在Contoller顶部。类似:
[Authorize]
public class XXController : Controller
{
}
但是因为我的项目需要使用第三部分的二进制DLL我们没有更改二进制dll上原始控制器的源代码,但我们可以忽略默认的授权-使用一些设置,然后我只想知道是否可以为XXController添加自定义的authorize属性使用代码?
这是我的CustomAuthorizeAttribute:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public bool IsOnlyAdminAccess {get ;set;}
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (Session.IsAdmin && !IsOnlyAdminAccess )
{
// redirect
}
}
}
因此,现在我认为global.aspx上是否存在可能。使用某种方式,如(只是想法)为特定控制器添加CustomAuthorizeAttribute:
AddCustomAttributeWayOrMethod(XXController, new CustomAuthorizeAttribute(IsOnlyAdminAccess = true));
一些朋友可能说我只是把它添加到GlobalFilterCollection
中,比如:
GlobalFilterCollection.Add(new CustomAuthorizeAttribute ());
但是我已经为全局控制器添加了它。我只需要我的XXController使用IsOnlyAdminAccess=true属性,其他控制器都不需要。
如果我是你,我会创建原始控制器的子类,并将我的属性放在子类上。
// this is the other controller in a dll, you don't have the source code
public controller TheirController {
// and this is yours, you have it in your code
// with your custom attribute
[CustomAttribute]
public controller YourController : TheirController {
// all actions are inherited