简体   繁体   English

ASP.NET Core API with WPF front-end „Newtonsoft.Json.JsonSerializationException” w mscorlib.dll Error converting value "Value cannot be null

[英]ASP.NET Core API with WPF front-end „Newtonsoft.Json.JsonSerializationException” w mscorlib.dll Error converting value "Value cannot be null

„Newtonsoft.Json.JsonSerializationException” w mscorlib.dll Error converting value "Value cannot be null. (Parameter 'userName')" to type 'Desktop.Model.UserAccess'. „Newtonsoft.Json.JsonSerializationException” w mscorlib.dll Error converting value "Value cannot be null. (Parameter 'userName')" to type 'Desktop.Model.UserAccess'.

I'm trying to make an request to my API with log in credentials such as Login and Password, and for unknown reason my API gets only NULLs instead of credentials i've put in the app.我正在尝试使用登录凭据(例如登录名和密码)向我的 API 发出请求,并且由于未知原因,我的 API 仅获得 NULL 而不是我放入应用程序的凭据。

My request sends correct values but API's model gets NULLs instead.我的请求发送了正确的值,但 API 的 model 改为 NULL。 Is it an issue with my backend or my front-end?是我的后端问题还是我的前端问题?

HTTP Request to my API: HTTP 对我的 API 的请求:

string api = ConfigurationManager.AppSettings["api"];字符串 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; }

Auth Controller:认证 Controller:

[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);
            }
    

You have an exception which you return as OK你有一个异常,你返回 OK

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

Login method returns a string Value cannot be null. (Parameter 'userName') Login方法返回一个字符串Value cannot be null. (Parameter 'userName') Value cannot be null. (Parameter 'userName') and another part of your application is trying to deserialise this and fails. Value cannot be null. (Parameter 'userName')和您的应用程序的另一部分试图反序列化它并失败。

I'm pretty sure the exception is thrown by var user = await _userManager.FindByNameAsync(model.UserName);我很确定异常是由var user = await _userManager.FindByNameAsync(model.UserName);引发的。 becuase model.UserName is null.因为model.UserName是 null。 You need to fix that part first.您需要先修复该部分。

暂无
暂无

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

相关问题 xamarin.forms-Newtonsoft.Json.JsonSerializationException:转换值时出错 - xamarin.forms - Newtonsoft.Json.JsonSerializationException: Error converting value .net Core 2.0 Web API - Newtonsoft.Json.JsonSerializationException - IQueryable - .net Core 2.0 Web API - Newtonsoft.Json.JsonSerializationException - IQueryable 错误:Newtonsoft.Json.JsonSerializationException - Error: Newtonsoft.Json.JsonSerializationException Newtonsoft.Json.JsonSerializationException:转换值时出错,无法从 System.String 转换或转换为 DashBoard.DashboardReport - Newtonsoft.Json.JsonSerializationException: Error converting value, Could not cast or convert from System.String to DashBoard.DashboardReport Swagger Newtonsoft.Json.JsonSerializationException:必需的属性“parcel_Triclops_Data”需要一个非空值 - Swagger Newtonsoft.Json.JsonSerializationException: Required property 'parcel_Triclops_Data' expects a non-null value Newtonsoft.Json.JsonSerializationException - Newtonsoft.Json.JsonSerializationException Newtonsoft.Json.JsonSerializationException: '无法反序列化当前的 JSON object (例如 {"name":"value"}) - Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) ModelState错误-Newtonsoft.Json.JsonSerializationException:无法填充列表类型System.Net.TrackingStringDictionary - ModelState error - Newtonsoft.Json.JsonSerializationException: Cannot populate list type System.Net.TrackingStringDictionary Newtonsoft.Json.JsonSerializationException(从'System.Data.SqlTypes.SqlDouble'的'Value'获取值时出错)序列化SqlGeography - Newtonsoft.Json.JsonSerializationException (Error getting value from 'Value' on 'System.Data.SqlTypes.SqlDouble) serializing SqlGeography Newtonsoft.Json.JsonSerializationException:从“Castle.Proxies.SalonProxy”上的“MyEntity”获取值时出错 - Newtonsoft.Json.JsonSerializationException: Error getting value from 'MyEntity' on 'Castle.Proxies.SalonProxy'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM