c# - 带有 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);
}
解决方案
你有一个异常,你返回 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
。您需要先修复该部分。
推荐阅读
- linux - 删除日期字符串早于 X 天的 yyyy-MM-dd 文件夹
- javascript - Laravel & Jquery - 用选择框填充文本框到另一个字段值
- javascript - 单元测试 MatDialog
- pip - 使用 conda 虚拟环境后将软件包安装到 Mac 桌面
- html - 谁能告诉我为什么位置:在 CSS 中的三次贝塞尔函数中需要固定?
- reactjs - 在 React 中,如何获取状态到 UI 中,然后通过数组对象进行映射
- python - 如何删除重复的三个列表中的相应值?
- php - 如何在每个主题的基础上创建唯一索引?
- python - python pandas re:search 抛出错误:预期的字符串或类似字节的对象
- sql - SELECT DISTINCT 返回 DATE 列的重复值