简体   繁体   中英

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

为什么不让SuperLoggerAttributeNormalLoggerAttribute继承并覆盖Log方法呢?

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)]

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