C# 如何在MVC上为某些特定的控制器使用代码添加自定义属性?

C# 如何在MVC上为某些特定的控制器使用代码添加自定义属性?,c#,asp.net,.net,asp.net-mvc,C#,Asp.net,.net,Asp.net Mvc,一般情况下,我们只是将该属性放在控制器顶部。比如: 但是因为我的项目需要使用第三部分二进制DLL。我们没有在二进制dll上更改原始控制器的源代码,但是我们可以忽略默认的授权使用某些设置,那么我只想知道是否可以为XXController使用代码添加自定义授权属性 这是我的自定义属性: public class CustomAuthorizeAttribute : AuthorizeAttribute { public bool IsOnlyAdminAccess {get ;set

一般情况下,我们只是将该属性放在控制器顶部。比如:

但是因为我的项目需要使用第三部分二进制DLL。我们没有在二进制dll上更改原始控制器的源代码,但是我们可以忽略默认的授权使用某些设置,那么我只想知道是否可以为XXController使用代码添加自定义授权属性

这是我的自定义属性:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
        public bool IsOnlyAdminAccess {get ;set;}

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (Session.IsAdmin && !IsOnlyAdminAccess )
            {
                  // redirect 
            }
         }
}
所以现在我想在global.aspx上可能有。使用某种方式,例如,为特定控制器添加CustomAuthorized属性:

AddCustomAttributeWayOrMethod(XXController, new CustomAuthorizeAttribute(IsOnlyAdminAccess = true));
一些朋友可能说我只是把它添加到GlobalFilterCollection中,比如:


但我已经为全局控制器添加了它。我只需要我的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

我可以用这种方式覆盖原始控制器和操作吗?
GlobalFilterCollection.Add(new CustomAuthorizeAttribute ());
 // 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