C# .NET CORE 如何获取自定义属性的值?

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

我有一个自定义属性 class 定义如下。

[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;
        }
    }
}

我将上述属性应用到另一个 class 如下。

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

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

如何获取 属性 AuthClientId 上 Encrypted=True 的值?

var config = new KeyVaultConfiguration();

// var authClientIdIsEncrypted = ??

在 .NET Framework 中,这很容易。在 .NET CORE 中,我认为这是可能的,但我没有看到任何文档。我相信您需要使用 System.Reflection,但具体如何使用?

添加 using System.Reflection 然后您可以使用 CustomAttributeExtensions.cs 中的扩展方法。

像这样的东西应该适合你:

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

你的情况

typeof(KeyVaultConfiguration).GetTypeInfo()
      .GetProperty("AuthClientId").GetCustomAttribute<EncryptedAttribute>();