简体   繁体   English

如何检查字符串是否与 static class 中任何变量的名称匹配?

[英]How to check if string matches the name from any variable in a static class?

When creating a new SigningCredentials instance the second constructor parameter is the signatureAlgorithm of type string .当创建一个新的SigningCredentials实例时,第二个构造函数参数是string类型的signatureAlgorithm

You don't have to use your own magic string, you can use static SecurityAlgorithms class eg SecurityAlgorithms.HmacSha256Signature .您不必使用自己的魔术字符串,可以使用 static SecurityAlgorithms class 例如SecurityAlgorithms.HmacSha256Signature

I read the algorithm from a config file and want to validate this string.我从配置文件中读取算法并想要验证这个字符串。 This string should contain a valid signatureAlgorithm .此字符串应包含有效的signatureAlgorithm Is there a simple way I could say有没有简单的方法可以说

(Pseudo Code) (伪代码)

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

so that one is not able to configure crap like identitySettings.TokenSignatureAlgorithm = "this is no algorithm";这样就无法像identitySettings.TokenSignatureAlgorithm = "this is no algorithm";

Without using reflection magic it is as simple as that:不使用反射魔法就这么简单:

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

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

PS附言

I purposelly didn't use reflection to solve your task, because controlling validation is often a must.我故意没有使用反射来解决您的任务,因为控制验证通常是必须的。 If you still want to be "bad boy", here you go - How can I get all constants of a type by reflection?如果您仍然想成为“坏男孩”,请在这里 go - 如何通过反射获得一个类型的所有常量?

Just initialize _allowedSecurityAlgorithms with constants returned from any method described there.只需使用从那里描述的任何方法返回的常量初始化_allowedSecurityAlgorithms

You can see what is happening when you pass wrong alorithm string, and then catch it:当你传递错误的算法字符串时,你可以看到发生了什么,然后抓住它:

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

the second option is to use Reflaction第二种选择是使用Reflaction

something list this:列出这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM