首页 > 解决方案 > 带有 WPF 前端“Newtonsoft.Json.JsonSerializationException”的 ASP.NET Core API w mscorlib.dll 错误转换值“值不能为空

问题描述

“Newtonsoft.Json.JsonSerializationException” w mscorlib.dll 错误转换值“值不能为空。(参数'userName')”键入'Desktop.Model.UserAccess'。

我正在尝试使用登录凭据(例如登录名和密码)向我的 API 发出请求,并且由于未知原因,我的 API 仅获取 NULL 而不是我放入应用程序中的凭据。

我的请求发送了正确的值,但 API 的模型改为 NULL。是我的后端问题还是我的前端问题?

对我的 API 的 HTTP 请求:

字符串 api = ConfigurationManager.AppSettings["api"];

    apiClient = new HttpClient();
    apiClient.BaseAddress = new Uri(api);
    apiClient.DefaultRequestHeaders.Accept.Clear();
    apiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

}

public async Task<UserAccess> Authenticate(string userName, string password)
{
    
  var data =  new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("grant_type", password),
    new KeyValuePair<string, string>("userName", userName),
    new KeyValuePair<string, string>("password", password),               


});
    
    try
    {
        using (HttpResponseMessage responseMessage = await apiClient.PutAsJsonAsync("api/Authentication/login", data))
        {
            if (responseMessage.IsSuccessStatusCode)
            {
                
                var result = await responseMessage.Content.ReadAsAsync<UserAccess>();
                result.GetType();                        
                return result;
            }
            else
            {
                throw new Exception(responseMessage.ReasonPhrase);
            }

        }
    }catch(Exception e)
    {
        Console.WriteLine(e.Message);
    }
    return null;
}

授权控制器:

[HttpPost]
        [Route("login")]
        public async Task<IActionResult> Login([FromBody] LoginModel model)
        {
            try
            {
                var user = await _userManager.FindByNameAsync(model.UserName);
                if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
                {
                    var userRoles = await _userManager.GetRolesAsync(user);

                    var authClaims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, user.UserName),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                };

                    foreach (var userRole in userRoles)
                    {
                        authClaims.Add(new Claim(ClaimTypes.Role, userRole));
                    }

                    var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"]));

                    var token = new JwtSecurityToken(
                        issuer: _configuration["JWT:ValidIssuer"],
                        audience: _configuration["JWT:ValidAudience"],
                        expires: DateTime.Now.AddHours(3),
                        claims: authClaims,
                        signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
                        );

                    return Ok(new
                    {
                        token = new JwtSecurityTokenHandler().WriteToken(token),
                        expiration = token.ValidTo,
                        userRoles
                    });
                }
                return Unauthorized();
            }
            catch(Exception e)
            {
                var exception = e.Message;
                return Ok(exception);
            }
    

标签: c#wpfasp.net-corehttp

解决方案


你有一个异常,你返回 OK

catch(Exception e)
{
    var exception = e.Message;
    return Ok(exception);
}

Login方法返回一个字符串Value cannot be null. (Parameter 'userName'),而您的应用程序的另一部分正试图反序列化它并失败。

我很确定异常是由 null 引发var user = await _userManager.FindByNameAsync(model.UserName);model.UserName。您需要先修复该部分。


推荐阅读