[英]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.