zoukankan      html  css  js  c++  java
  • 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";
    }
  • 相关阅读:
    Python爬虫基础——re模块的提取、匹配和替换
    Python爬虫基础——正则表达式
    Python爬虫基础——HTML、CSS、JavaScript、JQuery网页前端技术
    Python——面向对象(类)的基础疑难点
    简单易懂的ftp脚本自动登录教程
    如何完成述职报告或年终总结PPT
    nmon脚本——对Linux服务器的监控
    记——第一次服务器被挖矿
    vsftpd超实用技巧详解
    MySQL、Oracle、SqlServer的区别
  • 原文地址:https://www.cnblogs.com/ANPY/p/12431892.html
Copyright © 2011-2022 走看看