.NET PAGE分页

一、功能说明

  1. 当前端传入分页查询信息时,会校验并修改请求分页的信息
ini 复制代码
    public class RequestPage
    {

        public string? keyword { get; set; }

        private const int maxSize = 20;

        private int _pageNumber = 1;
        public int pageNumber
        {
            get => _pageNumber;
            set => _pageNumber = value < 1 ? 1 : value;   
        }
        private int _pageSize = 10 ; 
        public int pageSize
        {
            get => _pageSize;
            set => _pageSize = value < 1 ? 10 : ((value > maxSize) ? maxSize : value);
        }
    }

新建了一个类接受分页参数,实现了如下功能:

  • 默认每页最大展示20条,并且当没有参数传入时,默认展示第1页的前10条数据

  • 当传入的分页信息为负数时,展示第1页的前10条数据


  1. 默认会查询符合条件的所有信息,并且针对前端传递的pageSize和pageNumber截取并返回数据
csharp 复制代码
    public class ResponsePage<T>:List<T>
    {
        public int currentPage { get; private set; }
        public int totalPages { get; private set; }

        public int pageSize { get; private set; }

        public int totalCount { get; private set; }

        public bool hasPrevious => currentPage > 1;

        public bool hasNext => currentPage < totalPages;

        public ResponsePage(List<T> items,int count,int pageNumber,int pageSize)
        {
            totalCount = count;
            pageSize = pageSize;
            currentPage = pageNumber;
            totalPages = (int)Math.Ceiling(count / (double)pageSize);
            AddRange(items);
        }

        public static ResponsePage<T> Create(IQueryable<T> source,int pageNumber,int pageSize)
        {
            var count = source.Count();
            var items = source.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList();
            return new ResponsePage<T>(items, count, pageNumber, pageSize);
        }
    }

使用演示:

ini 复制代码
        [HttpGet(Name = nameof(GetUserInfo))]
        public object GetUserInfo([FromQuery]RequestPage? page)
        {

            // 初始化Bogus库
            var faker = new Faker();

            // 生成100个随机用户
            var users = Enumerable.Range(1, 100).Select(i =>
                new User
                {
                    Name = faker.Name.FullName(),
                    Age = faker.Random.Int(18, 60),
                    Email = faker.Internet.Email()
                });

            // 将用户列表转换为IQueryable对象
            var queryableUsers = users.AsQueryable();

            ResponsePage<User> res = ResponsePage<User>.Create(queryableUsers, page.pageNumber, page.pageSize);

            return res;
        }

  1. 请求头会捎带上一页下一页的请求地址以及分页信息
ini 复制代码
 ResponsePage<User> res = ResponsePage<User>.Create(queryableUsers, page.pageNumber, page.pageSize);

var previousLink = res.hasPrevious
    ? CreateResourceUri(page, ResourceUriType.PreviousPage)
    : null;

var nextLink = res.hasNext
   ? CreateResourceUri(page, ResourceUriType.NextPage)
   : null;

var paginationMetadata = new
{
    totalCount = res.totalCount,
    pageSize = res.pageSize,
    currentPage = res.currentPage,
    totalPages = res.totalPages,
    previousLink,
    nextLink
};
ini 复制代码
   private string CreateResourceUri(RequestPage page, ResourceUriType type)
        {
            switch (type)
            {
                case ResourceUriType.PreviousPage:
                    return Url.Link(nameof(GetUserInfo), new
                    {
                        pageNumber = page.pageNumber - 1,
                        pageSize = page.pageSize,
                        keyword = page.keyword
                    });
                case ResourceUriType.NextPage:
                    return Url.Link(nameof(GetUserInfo), new
                    {
                        pageNumber = page.pageNumber + 1,
                        pageSize = page.pageSize,
                        keyword = page.keyword
                    });
                default:
                    return Url.Link(nameof(GetUserInfo), new
                    {
                        pageNumber = page.pageNumber + 1,
                        pageSize = page.pageSize,
                        keyword = page.keyword
                    });
            }
        }

请求第一页的前3条数据,因为这是第一页,所以没有上一页,返回Null;而下一页信息,只是在这次请求的基础修改了pageNumber + 1

二、核心代码

ini 复制代码
using Bogus;
using MassTransit.Futures.Contracts;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using System.Security.AccessControl;
using  page_1.Controllers;
using System.Text.Encodings.Web;
using System.Text.Json;

namespace page_1.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {

        [HttpGet(Name = nameof(GetUserInfo))]
        public object GetUserInfo([FromQuery]RequestPage? page)
        {

            // 初始化Bogus库
            var faker = new Faker();

            // 生成100个随机用户
            var users = Enumerable.Range(1, 100).Select(i =>
                new User
                {
                    Name = faker.Name.FullName(),
                    Age = faker.Random.Int(18, 60),
                    Email = faker.Internet.Email()
                });

            // 将用户列表转换为IQueryable对象
            var queryableUsers = users.AsQueryable();

            ResponsePage<User> res = ResponsePage<User>.Create(queryableUsers, page.pageNumber, page.pageSize);

            var previousLink = res.hasPrevious
                ? CreateResourceUri(page, ResourceUriType.PreviousPage)
                : null;

            var nextLink = res.hasNext
               ? CreateResourceUri(page, ResourceUriType.NextPage)
               : null;

            var paginationMetadata = new
            {
                totalCount = res.totalCount,
                pageSize = res.pageSize,
                currentPage = res.currentPage,
                totalPages = res.totalPages,
                previousLink,
                nextLink
            };


            Response.Headers.Add("X-Pagination", JsonSerializer.Serialize(paginationMetadata,
                new JsonSerializerOptions
                {
                    Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                }));

            return res;
        }


        private string CreateResourceUri(RequestPage page, ResourceUriType type)
        {
            switch (type)
            {
                case ResourceUriType.PreviousPage:
                    return Url.Link(nameof(GetUserInfo), new
                    {
                        pageNumber = page.pageNumber - 1,
                        pageSize = page.pageSize,
                        keyword = page.keyword
                    });
                case ResourceUriType.NextPage:
                    return Url.Link(nameof(GetUserInfo), new
                    {
                        pageNumber = page.pageNumber + 1,
                        pageSize = page.pageSize,
                        keyword = page.keyword
                    });
                default:
                    return Url.Link(nameof(GetUserInfo), new
                    {
                        pageNumber = page.pageNumber + 1,
                        pageSize = page.pageSize,
                        keyword = page.keyword
                    });
            }
        }
    }


    public enum ResourceUriType
    {
        PreviousPage, NextPage
    }


    // 定义一个用户类
    public class User
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Email { get; set; }
    }



    public class RequestPage
    {

        public string? keyword { get; set; }

        private const int maxSize = 20;

        private int _pageNumber = 1;
        public int pageNumber
        {
            get => _pageNumber;
            set => _pageNumber = value < 1 ? 1 : value;   
        }
        private int _pageSize = 10 ; 
        public int pageSize
        {
            get => _pageSize;
            set => _pageSize = value < 1 ? 10 : ((value > maxSize) ? maxSize : value);
        }
    }

    public class ResponsePage<T>:List<T>
    {
        public int currentPage { get; private set; }
        public int totalPages { get; private set; }

        public int pageSize { get; private set; }

        public int totalCount { get; private set; }

        public bool hasPrevious => currentPage > 1;

        public bool hasNext => currentPage < totalPages;

        public ResponsePage(List<T> items,int count,int pageNumber,int pageSize)
        {
            totalCount = count;
            pageSize = pageSize;
            currentPage = pageNumber;
            totalPages = (int)Math.Ceiling(count / (double)pageSize);
            AddRange(items);
        }

        public static ResponsePage<T> Create(IQueryable<T> source,int pageNumber,int pageSize)
        {
            var count = source.Count();
            var items = source.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList();
            return new ResponsePage<T>(items, count, pageNumber, pageSize);
        }
    }

}
相关推荐
Ai 编码助手5 小时前
在 Go 语言中如何高效地处理集合
开发语言·后端·golang
小丁爱养花5 小时前
Spring MVC:HTTP 请求的参数传递2.0
java·后端·spring
Channing Lewis5 小时前
什么是 Flask 的蓝图(Blueprint)
后端·python·flask
轩辕烨瑾6 小时前
C#语言的区块链
开发语言·后端·golang
栗豆包8 小时前
w175基于springboot的图书管理系统的设计与实现
java·spring boot·后端·spring·tomcat
萧若岚9 小时前
Elixir语言的Web开发
开发语言·后端·golang
Channing Lewis9 小时前
flask实现重启后需要重新输入用户名而避免浏览器使用之前已经记录的用户名
后端·python·flask
Channing Lewis9 小时前
如何在 Flask 中实现用户认证?
后端·python·flask
一只爱吃“兔子”的“胡萝卜”10 小时前
2.Spring-AOP
java·后端·spring
AI向前看10 小时前
PHP语言的软件工程
开发语言·后端·golang