c# - API 调用导致 System.InvalidCastException: Specified cast is not valid
问题描述
我有一个方法可以从 API 获取员工列表,然后将它们存储在 ObservableCollection 中以显示在 ListView 上。但是,我没有运气,因为我不断收到此错误“System.InvalidCastException:指定的演员表无效”。
我以为是列表,但令我惊讶的是,即使删除作业仍然会使应用程序崩溃。我发现有趣的是,在API 完成并var employees
填充后,代码将跳回 API 调用的右花括号,然后返回所述错误。任何帮助深表感谢。请在下面查看我的代码:
视图模型
public class EmployeeListViewModel : BaseViewModel
{
private IUserService _userService { get; set; }
public EmployeeListViewModel(IUserService userService)
{
_userService = userService;
GetEmployees();
}
private async void GetEmployees()
{
var employees = await _userService.GetEmployees();
Employees = new MvxObservableCollection<User>(employees);
}
private MvxObservableCollection<User> _employees;
public MvxObservableCollection<User> Employees
{
get => _employees;
set { SetProperty(ref _employees, value); }
}
}
服务
public async Task<List<User>> GetEmployees()
{
string url = $"{IpAddress}/{_controllerRoute}/getemployees";
var content = await _httpClient.GetStringAsync(url);
return JsonConvert.DeserializeObject<List<User>>(content);
}
模型
public class User
//Simply copying IdentityUser, as this is the object being returned from the server
{
public virtual string Id { get; set; }
public virtual string UserName { get; set; }
public virtual string NormalizedUserName { get; set; }
public virtual string Email { get; set; }
public virtual string NormalizedEmail { get; set; }
public virtual bool EmailConfirmed { get; set; }
public virtual string PasswordHash { get; set; }
public virtual string SecurityStamp { get; set; }
public virtual string ConcurrencyStamp { get; set; }
public virtual string PhoneNumber { get; set; }
public virtual bool PhoneNumberConfirmed { get; set; }
public virtual bool TwoFactorEnabled { get; set; }
public virtual DateTime? LockoutEnd { get; set; }
public virtual bool LockoutEnabled { get; set; }
public virtual int AccessFailedCount { get; set; }
}
解决方案
推荐阅读
- git - 如何移动一些已发布的提交,包括合并到分支并稍后将它们合并回来
- c# - Xamarin Forms - iOS - 根据屏幕方向更改初始屏幕
- google-bigquery - bigquery google.api.client 获取表列表 API
- macos - 在异步加载文件时更新 NSWindow 内容
- arrays - 用数组转置数据集
- javascript - 在 ASP.net MVC Web 应用程序中跟踪注销时间
- java - 相机 API - 如何专注于图像中多边形的中心?
- matrix - glmnet 输入错误,输入矩阵的格式不正确
- bash - 错误:-测试: ing: 一元运算符预期
- java - 为什么我创建的目录没有同时出现在图库和 Google 相册中?