Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# .NET CORE how to get the value of a custom attribute?

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?

like image 669
SamDevx Avatar asked Mar 09 '17 07:03

SamDevx


1 Answers

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>();
like image 153
Set Avatar answered Oct 11 '22 13:10

Set