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

北城余情 提交于 2019-12-07 03:22:48

问题


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:


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>();


来源:https://stackoverflow.com/questions/42689283/c-sharp-net-core-how-to-get-the-value-of-a-custom-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!