C#:ArgumentNullException:字符串引用未设置为字符串的实例。参数名称:s System.Text.Encoding.GetBytes(string s)

Posted

技术标签:

【中文标题】C#:ArgumentNullException:字符串引用未设置为字符串的实例。参数名称:s System.Text.Encoding.GetBytes(string s)【英文标题】:C#:ArgumentNullException: String reference not set to an instance of a String. Parameter name: 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"
    
  

请帮助解决此错误

【问题讨论】:

【参考方案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 工作谢谢马丁科斯特洛

以上是关于C#:ArgumentNullException:字符串引用未设置为字符串的实例。参数名称:s System.Text.Encoding.GetBytes(string s)的主要内容,如果未能解决你的问题,请参考以下文章

C#高级特性

C# EntryPointNotFoundException

System.ArgumentNullException: '值不能为空。参数名称:输入'Xamarin?

在此处添加 try-catch 构造以捕获“ArgumentNullException”

在构造函数中抛出 ArgumentNullException?

获得未处理的异常:System.ArgumentNullException