ASP.NET CORE 2.1-FromQuery不起作用?

时间:2018-07-18 17:35:23

标签: c# asp.net-core asp.net-core-webapi

我有一个用于捕获所有参数的类:

public class UserParams
{
    private const int MaxPageSize = 50;
    public int PageNumber { get; set; } = 1;
    private int pageSize = 10;
    public int PageSize
    {
        get { return pageSize;}
        set { pageSize = (value > MaxPageSize) ? MaxPageSize : value;}
    }

    public int UserId { get; set; }        
    public string OrderBy { get; set; }
    public bool isAll {get; set;} = true; 
    public bool isManagers { get; set; } = false;
    public bool isPartners { get; set; } = false;
}

和我的控制器:

[HttpGet]
public async Task<IActionResult> GetUsers([FromQuery] UserParams userParams)
{
    var users = await _appRepo.GetUsers(userParams);
    var usersDto = _mapper.Map<IEnumerable<UserSimpleDto>>(users);
    Response.AddPagination(users.CurrentPage, users.PageSize, users.TotalCount, users.TotalPages);
    return Ok(usersDto);
}    

当我的appRepo.GetUsers:

public async Task<PagedList<User>> GetUsers(UserParams userParams)
{
    var users = _context.Users.OrderByDescending(p => p.FirstName).AsQueryable();
    if(userParams.isManagers)
    {
        users = users.Where( u => u.IsManager == true);
    }

    if(userParams.isPartners)
    {
        users = users.Where( u => u.IsPartner == true);
    }

    return await PagedList<User>.CreateAsync(users, userParams.PageNumber, userParams.PageSize);
}

我尝试使用Postman调试代码: http://localhost:5000/api/user?isManagers=1 要么 http://localhost:5000/api/user?isManagers=true

但是参数isManagers似乎仍然是错误的(结果仍然是获得所有用户)

如何修复此错误?

1 个答案:

答案 0 :(得分:0)

您是否尝试过将FromQuery属性放在类的每个属性上?

像这样:

public class UserParams
{
    private const int MaxPageSize = 50;
    [FromQuery] 
    public int PageNumber { get; set; } = 1;

    Etc
}