【问题标题】:System.ArgumentNullException: 'String reference not set to an instance of a String. Parameter name: s'System.ArgumentNullException: '字符串引用未设置为字符串的实例。参数名称:s'
【发布时间】:2019-08-24 00:38:33
【问题描述】:

当我提交注册表时出现此错误:

System.ArgumentNullException: '字符串引用未设置为字符串的实例。 参数名称:s'

它来自散列密码类

public static class Crypto
{
    public static string Hash(string value)
    {
        return Convert.ToBase64String(
            SHA256.Create()
                .ComputeHash(Encoding.UTF8.GetBytes(value)));
    }
}

【问题讨论】:

  • value的值是多少?

标签: c# .net cryptography


【解决方案1】:

在调用其余方法之前检查value 是否为空(或空):

public static string Hash(string value)
{
    if (String.IsNullOrEmpty(value))
        throw new ArgumentNullException(nameof(value));

    var bytes = Encoding.UTF8.GetBytes(value);
    var hash = SHA256.Create().ComputeHash(bytes)
    return Convert.ToBase64String(hash);
}

将每个方法的结果保存在自己的变量中也有助于您调试和更好地理解流程。

【讨论】:

    猜你喜欢
    • 2020-06-14
    • 2019-12-07
    • 2021-08-23
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 2014-11-28
    • 2022-11-18
    • 1970-01-01
    相关资源
    最近更新 更多