随缘 我不喜欢太复杂的东西

导航

ASP.NET Core 3.1 Web API GET方法。(支持查询、排序、分页)

Controllers中的代码

//获取指定分类的所有项目
[HttpGet(Name= nameof(GetDictionarys))]
public async Task<ActionResult<DictionarysItemViewModel>> GetDictionarys(string ClassKey, 
        [FromQuery]DictionaryParameters pars)
{
    if (string.IsNullOrWhiteSpace(ClassKey) || !await dbc.DictionaryClasses.AnyAsync(a => a.Key == ClassKey))
    {
        return NotFound("没有找到此字典分类");
    }

    var items = dbc.Dictionarys.Where(a => a.ClassKey == ClassKey);

    //搜索
    if (!string.IsNullOrWhiteSpace(pars.Q))
    {
        pars.Q = pars.Q.Trim();
        items = items.Where(a => a.Text.Contains(pars.Q));
    }

    //排序
    if (!string.IsNullOrWhiteSpace(pars.OrderBy))
    {
        var orderByAfterSplit = pars.OrderBy.Split(",");
        foreach (var orderByClause in orderByAfterSplit.Reverse())
        {
            var trimmedOrderByClause = orderByClause.Trim();//去除空格后的查询条件

            var orderDescending = trimmedOrderByClause.EndsWith(" desc");//是否倒序

            var indexOfFirstSpace = trimmedOrderByClause.IndexOf(" ", StringComparison.Ordinal);

            var propertyName = indexOfFirstSpace == -1
                ? trimmedOrderByClause
                : trimmedOrderByClause.Remove(indexOfFirstSpace);//查询条件名称

            var propertyMappingValue = "";
            switch (propertyName.ToLower())//允许的搜索条件
            {
                case "times":propertyMappingValue = "times"; break;
                case "key": propertyMappingValue = "Key"; break;
                case "text": propertyMappingValue = "Text"; break;
                default: propertyMappingValue = "Key"; break;
            }

            items = items.OrderBy(propertyMappingValue + (orderDescending ? " descending" : " ascending"));
        }
    }

    //分页
    items = items.Skip((pars.PageNumber - 1) * pars.PageSize).Take(pars.PageSize);
    var count = await items.CountAsync();
    var TotalPages = (int)Math.Ceiling(count / (double)pars.PageSize);
    var PrevPageLink = (pars.PageNumber > 1) ?
            Url.Link(nameof(GetDictionarys),
            new
            {
                PageNumber = pars.PageNumber - 1,
                pars.PageSize,
                pars.Q,
                pars.OrderBy
            }) :
            null;
    var NextPageLink = (pars.PageNumber < TotalPages) ?
        Url.Link(nameof(GetDictionarys),
        new
        {
            PageNumber = pars.PageNumber + 1,
            pars.PageSize,
            pars.Q,
            pars.OrderBy
        }) :
        null;

    var paginationMetadata = new
    {
        TotalCount=count,
        pars.PageSize,
        CurrentPage=pars.PageNumber,
        TotalPages,
        PrevPageLink,
        NextPageLink
    };
    Response.Headers.Add("X-Pagination",
        JsonSerializer.Serialize(paginationMetadata, new JsonSerializerOptions
        { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }));//向Header中添加分页信息

    //输出结果
    var r = items.Select(a => new DictionarysItemViewModel()
        {
            Key = a.Key,
            Text = a.Text,
            times = a.times
        }).ToList();

    return Ok(r);
}

 

//参数表

public class DictionaryParameters
{
    private const int MaxPageSize = 100;
    public string Q { get; set; }
    public int PageNumber { get; set; } = 1;
    private int _pageSize = 20;

    public int PageSize
    {
        get => _pageSize;
        set => _pageSize = (value > MaxPageSize) ? MaxPageSize : value;
    }

    public string OrderBy { get; set; } = "times desc";
}

 

posted on 2020-03-07 00:17  随缘py  阅读(1121)  评论(0编辑  收藏  举报