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

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

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

我将以上属性应用于另一个类,如下所示。

 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().GetTypeInfo() .GetProperty().GetCustomAttribute(); 

在你的情况下

 typeof(KeyVaultConfiguration).GetTypeInfo() .GetProperty("AuthClientId").GetCustomAttribute();