8

I have a custom attribute class defined as follows.

[AttributeUsage(AttributeTargets.Property, Inherited = false)]
internal class EncryptedAttribute : System.Attribute
{
    private bool _encrypted;
    public EncryptedAttribute(bool encrypted)
    {
        _encrypted = encrypted;
    }

    public virtual bool Encrypted
    {
        get
        {
            return _encrypted;
        }
    }
}

I applied the above attribute to another class as follows.

public class KeyVaultConfiguration
{
    [Encrypted(true)]
    public string AuthClientId { get; set; } = "";

    public string AuthClientCertThumbprint { get; set; } = "";
}

How do I get the value of Encrypted=True on property AuthClientId?

var config = new KeyVaultConfiguration();

// var authClientIdIsEncrypted = ??

In .NET Framework, this was easy. In .NET CORE, I think this is possible but I don't see any documentation. I believe you need to use System.Reflection but exactly how?

1 Answer 1

19

Add using System.Reflection and then you may use extension methods from CustomAttributeExtensions.cs.

Something like this should work for you:

typeof(<class name>).GetTypeInfo()
      .GetProperty(<property name>).GetCustomAttribute<YourAttribute>();

in your case

typeof(KeyVaultConfiguration).GetTypeInfo()
      .GetProperty("AuthClientId").GetCustomAttribute<EncryptedAttribute>();
Sign up to request clarification or add additional context in comments.

1 Comment

The link is dead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.