views:

370

answers:

4

Hi, I have a base class with an attribute and I want to hide it in a derived class. Is there any way to do this other than using reflection?

[Authorize(Roles = "User,Admin,Customs")]
public abstract class ApplicationController : Controller
{
}

// hide the Authorize attribute
public class ErrorController : ApplicationController
{
}
+1  A: 

If it was a method/prop, you could re-declare (new) the member without the offending attribute. I don't know of a way with class-level attributes.

public new SomeType Foo() { return base.Foo(); }
Marc Gravell
A: 

You can specify the 'AttributeUage' attribute on your Attribute class, like this:

[AttributeUsage(AttributeTargets.Class, Inherited=false)]
public class AuthorizeAttribute : Attribute
{
}

Then, classes that derive from the class where you've applied the attribute, will not inherit the attribute.

Ow, now I realize that the Authorize attribute is not a custom attribute.

Frederik Gheysels
Yes, this is a class created by the Microsoft team in System.Web.MVC.
PaulN
A: 

You could override the AuthorizeAttribute with your own class and specify it to not be inherited.

[AttributeUsage(AttributeTargets.Class, Inherited=false)]
public class NonInheritedAuthorizeAttribute : AuthorizeAttribute
{
    // Constructors, etc.
}

Now you can specify which class to use, as long as you own ApplicationController.

Arc
I thought about doing this as well, but I try to use Microsoft classes whenever possible so I opted to just remove the Authorize attribute from my base class and add it to each derived controller.
PaulN
+3  A: 
Roger Pate
Well, it would of been nice to set a default authorization for the site using the base class. I only have 1 Controller out of 9 that only allows Admins. Since it doesn't seem possible to remove a base class attribute then this is the soundest advice. I have removed [Authorize(Roles = "User,Admin,Customs")] and I will just set it in every controller.
PaulN