简体   繁体   中英

How add custom AuthorizeAttribute for some specific Controller use code on MVC?

The general case we just put the Attribute on the Contoller top . like:

[Authorize]
public class XXController : Controller
{

}

But because My project need use the third part binary DLL. we don't have the source code for change the original controller on the binary dll, but we can ignore the default authorize use some setting for it, then I just want to know Is there possible to add custom Authorize Attribute to for the XXController use code ?

This is my CustomAuthorizeAttribute:

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

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (Session.IsAdmin && !IsOnlyAdminAccess )
            {
                  // redirect 
            }
         }
}

So now I think Is there Maybe on global.aspx. use some way like( just idea ) add the CustomAuthorizeAttribute for the specific Controller:

AddCustomAttributeWayOrMethod(XXController, new CustomAuthorizeAttribute(IsOnlyAdminAccess = true));

Some friend maybe said I just add it to GlobalFilterCollection , like:

GlobalFilterCollection.Add(new CustomAuthorizeAttribute ());

But I already add it for global controller. I just need my XXController use IsOnlyAdminAccess = true property, other controller all don't need that.

If I were you, I would create a subclass of the original controller and put my attribute over the child class.

 // 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM