【问题标题】:C#:ArgumentNullException: String reference not set to an instance of a String. Parameter name: s System.Text.Encoding.GetBytes(string s)C#:ArgumentNullException:字符串引用未设置为字符串的实例。参数名称:s System.Text.Encoding.GetBytes(string s)
【发布时间】:2021-08-23 02:30:52
【问题描述】:

我有这种方法可以使用 c# .netcore 3.1 版本生成 jwt 令牌。

      [HttpPost]
        public async Task<IActionResult> CreateToken([FromBody] LoginViewModel model)
        {
            if( ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(model.Username);

                if (user != null)
                {
                    var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false); 

                    if (result.Succeeded)
                    {
                        // Create the token
                        var claims = new[]
                        {
                            new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                            new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName),
                        };

                        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
                        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                        var token = new JwtSecurityToken(
                            _config["Tokens:Issuer"], 
                            _config["Tokens:Audience"], 
                            claims,
                            signingCredentials: creds,
                            expires: DateTime.UtcNow.AddMinutes(30));

                        var results = new
                        {
                            token = new JwtSecurityTokenHandler().WriteToken(token),
                            expiration = token.ValidTo
                        };
                        return Created("", results);
                        
                    }
                }
            }

            return BadRequest();
        }
    }

当我通过邮递员调用 CreateToken 方法 API 时:

    When I call this API via postman :
    http://localhost:8888/account/CreateToken

我收到了这个错误

    
    System.ArgumentNullException: String reference not set to an instance of a String. (Parameter 's')
   at System.Text.Encoding.GetBytes(String s)
   at DutchTreat.Contollers.AccountController.CreateToken(LoginViewModel model) in E:\.NET Core and Angular\DutchTreat\Contollers\AccountController.cs:line 101

经过一些调试,我发现错误来了,因为这条线

 var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));

这是我使用的配置文件

{
  "Color": {
    "Favourite": "Blue"
  },
  "ConnectionStrings": {
    "DutchContextDb": "Data Source=(localdb)\\ProjectsV13;Initial Catalog=DutchTreatDb;Integrated Security=True;Connect Timeout=30;MultipleActiveResultSets=true"
  },
  "Logging": {
    "LogLevel": {
      "DutchTreat": "Information",
      "Microsoft": "Warning"
    },
    "Tokens": {
      "Key": "a;sdlkfja; lsdkfj ;alksdfj ;alksdfj; aiefj;lskij;flds",
      "Issuer": "http://localhost:8888",
      "Audience": "http://localhost:8888"
    }
  }
}

请帮助解决此错误

【问题讨论】:

    标签: c# asp.net-core jwt postman rest


    【解决方案1】:

    使用正确的密钥:

    _config["Logging:Tokens:Key"]
    

    或修复您的 JSON:

    {
      "Color": {
        "Favourite": "Blue"
      },
      "ConnectionStrings": {
        "DutchContextDb": "Data Source=(localdb)\\ProjectsV13;Initial Catalog=DutchTreatDb;Integrated Security=True;Connect Timeout=30;MultipleActiveResultSets=true"
      },
      "Logging": {
        "LogLevel": {
          "DutchTreat": "Information",
          "Microsoft": "Warning"
        }
      },
      "Tokens": {
        "Key": "a;sdlkfja; lsdkfj ;alksdfj ;alksdfj; aiefj;lskij;flds",
        "Issuer": "http://localhost:8888",
        "Audience": "http://localhost:8888"
      }
    }
    

    【讨论】:

    • 修复 json 工作谢谢马丁科斯特洛
    猜你喜欢
    • 2019-12-07
    • 2020-06-14
    • 1970-01-01
    • 2011-08-19
    • 2010-09-24
    • 1970-01-01
    • 2020-09-07
    • 2019-11-06
    • 1970-01-01
    相关资源
    最近更新 更多