Chi Chan
Chi Chan

Reputation: 12350

C# Attributes that figures out if another attribute is applied

I am working on a Asp.net MVC project and I am wondering if there is a way for the attributes to talk to other attributes.

For example, I have the following attributes

public class SuperLoggerAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        //Do something super
    }
}

public class NormalLoggerAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        //Do something normal ONLY if the super attribute isn't applied 
    }
}

And I have the following controllers

[NormalLogger]
public class NormalBaseController : Controller
{

}

public class PersonController: NormalBaseController
{

}

[SuperLogger]
public class SuperController: NormalBaseControler
{

}

So basically, I want my SuperController to use SuperLogger and ignore NormalLogger (which was applied in the base), and PersonController should use the NormalLogger since it's not "overrided" by the SuperLogger. Is there a way to do that?

Thanks,

Chi

Upvotes: 0

Views: 163

Answers (2)

Tom Vervoort
Tom Vervoort

Reputation: 5108

I think this should work:

public enum LoggerTypes
{
    Normal,
    Super
}

public class LoggerAttribute : ActionFilterAttribute
{
    public LoggerAttribute() : base()
    {
        LoggerType = LoggerTypes.Normal;
    }

    public LoggerAttribute(LoggerTypes loggerType) : base()
    {
        LoggerType = loggerType;
    }

    public LoggerTypes LoggerType
    {
        get; 
        set;
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (LoggerType == LoggerTypes.Super)
        {
            //
        }
        else
        {
            //
        }
    }

Usage:

[Logger(LoggerTypes.Normal)]

or

[Logger(LoggerTypes.Super)]

Upvotes: 0

Matt Mills
Matt Mills

Reputation: 8792

Why not just have SuperLoggerAttribute inherit from NormalLoggerAttribute and override the Log method?

Upvotes: 1

Related Questions