【问题标题】:How to check if string matches the name from any variable in a static class?如何检查字符串是否与静态类中任何变量的名称匹配?
【发布时间】:2020-12-02 14:59:41
【问题描述】:

创建一个新的SigningCredentials 实例时,第二个构造函数参数是string 类型的signatureAlgorithm

您不必使用自己的魔术字符串,您可以使用静态SecurityAlgorithms 类,例如SecurityAlgorithms.HmacSha256Signature.

我从配置文件中读取算法并想要验证此字符串。此字符串应包含有效的signatureAlgorithm。有没有简单的方法可以说

(伪代码)

if (SecurityAlgorithms.Contains(identitySettings.TokenSignatureAlgorithm))
{
    // validation failed
}

这样就不能像identitySettings.TokenSignatureAlgorithm = "this is no algorithm";那样配置废话

【问题讨论】:

标签: c#


【解决方案1】:

不使用反射魔法就这么简单:

private readonly HashSet<string> _allowedSecurityAlgorithms = new HashSet<string>(StringComparison.OrdinalIgnoreCase) 
    {
        SecurityAlgorithms.A, 
        SecurityAlgorithms.B, 
        SecurityAlgorithms.C
    };

if (!_allowedSecurityAlgorithms.Contains(identitySettings.TokenSignatureAlgorithm))
{
    // validation failed
}

附言

我故意不使用反射来解决您的任务,因为控制验证通常是必须的。如果你还想做“坏小子”,那就去吧-How can I get all constants of a type by reflection?

只需使用从那里描述的任何方法返回的常量初始化_allowedSecurityAlgorithms

【讨论】:

  • 怎么样? :) if (!typeof(SecurityAlgorithms).GetFields().Any(fieldInfo =&gt; fieldInfo.Name.Equals(identitySettings.TokenSignatureAlgorithm))) // failed
  • 您可以根据需要使用反射。最好不要普遍使用它——你失去了对性能、你编写的代码、你的同事编写的代码的控制。例如,尝试对它进行单元测试,或者运行几千次并与直接进行比较。如果它满足您的业务任务 - 它总是好的方法,但从长远来看并不总是好的。
【解决方案2】:

当你传递错误的算法字符串时,你可以看到发生了什么,然后抓住它:

try
{
    var signCredentials = new SigningCredentials(a,b,c,d);
}
catch(Exception e)
{
// validation failed
}

第二个选项是使用Reflaction

列出这个:

string[] algs = typeof(SecurityAlgorithms)
.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
.Select(pi => pi.GetRawConstantValue().ToString())
.ToArray();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-30
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 2013-12-15
    • 2016-10-03
    • 1970-01-01
    • 2012-05-12
    相关资源
    最近更新 更多