简体   繁体   中英

How to check if class attribute defined in StackFrame?

I need to skip System.Diagnostics.StackFrame routes of my class in my exeption middleware.

Currently I can check in exception StackFrame if my methods have [StackTraceHidden] attribute.

For example this is how my class looks now (attribute needs to mark every method):

public class ValidString
{
    private string _value;

    [StackTraceHidden]
    public ValidString(string value)
    {
        Validate(value);
        _value = value;
    }

    [StackTraceHidden]
    private void Validate(string value)
    {
        if (string.IsNullOrWhiteSpace(value))
            throw new ArgumentException(nameof(value));  
    }

    [StackTraceHidden]
    public static implicit operator ValidString(string value)
    {
        if (value == null)
            return null;

        return new ValidString(value);
    }
}

And how I skip marked methods in StackFrame :

    foreach(StackFrame stackFrame in stackTrace.GetFrames())
        if (!stackFrame.GetMethod().IsDefined(typeof(StackTraceHiddenAttribute), true))
            return stackFrame;

It doesn't feel right to mark every method of classes I need to skip with these attributes. I want mark my class with [StackTraceHidden] attribute to skip all StackFrame 's that are registered at this class .

This is how I want it to be (attribute only marks class):

[StackTraceHidden]
public class ValidString
{
    private string _value;

    public ValidString(string value)
    {
        Validate(value);
        _value = value;
    }

    private void Validate(string value)
    {
        if (string.IsNullOrWhiteSpace(value))
            throw new ArgumentException(nameof(value));
    }

    public static implicit operator ValidString(string value)
    {
        if (value == null)
            return null;

        return new ValidString(value);
    }
}

And that's how I imagine to skip whole class from StackFrame :

    foreach(StackFrame stackFrame in stackTrace.GetFrames())
        if (!stackFrame.GetClass().IsDefined(typeof(StackTraceHiddenAttribute), true))
            return stackFrame;

In short: How to do something like this?

bool markedWithSomeAttribute = stackTrace.GetFrame(i).GetClass().IsDefined(typeof(SomeAttribute), true);

Got answer here: https://docs.microsoft.com/en-us/answers/questions/907789/how-to-check-if-class-attribute-defined-in-stackfr.html

The solution:

bool marked = stackFrame.GetMethod().DeclaringType.CustomAttributes.Any(ca => ca.AttributeType == typeof(StackTraceHiddenAttribute));

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