首页 > 解决方案 > 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; }
}

标签: c#xamarinxamarin.formsmvvmcross

解决方案


推荐阅读