开发实战:asp.net core + ef core 实现动态可扩展的分页方案
统一请求参数先定义一个公共的QueryParameters解决这个问题public class QueryParameters{private const int MaxPageSize 100;private int _pageSize 10;public int PageNumber { get; set; } 1;// 限制最大值防止前端传一个很大数值把数据库搞崩了public int PageSize{get _pageSize;set _pageSize value MaxPageSize ? MaxPageSize : value;}// 支持多字段排序格式name desc,price ascpublic string? SortBy { get; set; }// 通用关键词搜索public string? Search { get; set; }// 动态过滤条件public ListFilterItem Filters { get; set; } [];// 要返回的字段逗号分隔id,name,price不传则返回全部public string? Fields { get; set; }}ASP.NET Core 的模型绑定会自动把 query string 映射到这个对象不需要手动解析。后续如果某个接口有额外参数继承它加字段就行不用每次从头定义。统一响应包装器返回值也统一一下把分页信息和数据放在一起调用方就不用自己拼了public class PagedResponseT{// IReadOnlyList 防止外部随意修改集合public IReadOnlyListT Data { get; init; } [];public int PageNumber { get; init; }public int PageSize { get; init; }public int TotalRecords { get; init; }public int TotalPages (int)Math.Ceiling(TotalRecords / (double)PageSize);public bool HasNextPage PageNumber TotalPages;public bool HasPreviousPage PageNumber 1;}Data 是任意类型的集合用IReadOnlyList防止被意外修改。TotalPages、HasNextPage和HasPreviousPage三个是计算属性不需要单独赋值。扩展方法把分页、排序、过滤都做成IQueryableT的扩展方法用起来像链式调用调用的地方看起来会很干净。分页public static IQueryableT ApplyPaginationT(this IQueryableT query,int pageNumber,int pageSize){return query.Skip((pageNumber - 1) * pageSize).Take(pageSize);}动态排序解析name desc,price asc这样的字符串动态生成排序表达式。用反射就能做到不需要额外的库public static IQueryableT ApplySortT(this IQueryableT query,string? sortBy){if (string.IsNullOrWhiteSpace(sortBy))return query;var orderParams sortBy.Split(,, StringSplitOptions.RemoveEmptyEntries);var isFirst true;foreach (var param in orderParams){var parts param.Trim().Split( );var propertyName parts[0];var isDesc parts.Length 1 parts[1].Equals(desc, StringComparison.OrdinalIgnoreCase);// 用反射找属性找不到就跳过避免抛异常var prop typeof(T).GetProperty(propertyName,BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);if (prop null) continue;// 构建表达式树x x.PropertyNamevar paramExpr Expression.Parameter(typeof(T), x);var body Expression.Property(paramExpr, prop);var lambda Expression.Lambda(body, paramExpr);var methodName isFirst? (isDesc ? OrderByDescending : OrderBy): (isDesc ? ThenByDescending : ThenBy);var method typeof(Queryable).GetMethods().First(m m.Name methodName m.GetParameters().Length 2).MakeGenericMethod(typeof(T), prop.PropertyType);query (IQueryableT)method.Invoke(null, [query, lambda])!;isFirst false;}return query;}也可以考虑System.Linq.Dynamic.Core这个库。动态过滤这是扩展性最强的一块。前端传字段名 操作符 值后端用表达式树动态拼 Where 条件不需要每加一个筛选项就改后端代码。先定义过滤条件的数据结构public class FilterItem{// 字段名对应实体属性不区分大小写public string Field { get; set; } string.Empty;// 操作符eq、neq、contains、startswith、endswith、// gt、gte、lt、lte、between、in、isnull、isnotnullpublic string Op { get; set; } eq;// 值between 用逗号分隔两个值in 用逗号分隔多个值public string? Value { get; set; }}然后实现过滤扩展方法public static IQueryableT ApplyFiltersT(this IQueryableT query,IEnumerableFilterItem filters){foreach (var filter in filters){var prop typeof(T).GetProperty(filter.Field,BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);// 找不到属性或者没有 [Filterable] 标记就跳过if (prop null || !prop.IsDefined(typeof(FilterableAttribute), false))continue;var param Expression.Parameter(typeof(T), x);var member Expression.Property(param, prop);Expression? condition null;switch (filter.Op.ToLower()){case eq:condition Expression.Equal(member, ParseConstant(filter.Value, prop.PropertyType));break;case neq:condition Expression.NotEqual(member, ParseConstant(filter.Value, prop.PropertyType));break;case gt:condition Expression.GreaterThan(member, ParseConstant(filter.Value, prop.PropertyType));break;case gte:condition Expression.GreaterThanOrEqual(member, ParseConstant(filter.Value, prop.PropertyType));break;case lt:condition Expression.LessThan(member, ParseConstant(filter.Value, prop.PropertyType));break;case lte:condition Expression.LessThanOrEqual(member, ParseConstant(filter.Value, prop.PropertyType));break;case contains:condition Expression.Call(member,typeof(string).GetMethod(Contains, [typeof(string)])!,Expression.Constant(filter.Value ?? string.Empty));break;case startswith:condition Expression.Call(member,typeof(string).GetMethod(StartsWith, [typeof(string)])!,Expression.Constant(filter.Value ?? string.Empty));break;case endswith:condition Expression.Call(member,typeof(string).GetMethod(EndsWith, [typeof(string)])!,Expression.Constant(filter.Value ?? string.Empty));break;case between:// value 格式10,100var rangeParts filter.Value?.Split(,) ?? [];if (rangeParts.Length 2){var lower ParseConstant(rangeParts[0].Trim(), prop.PropertyType);var upper ParseConstant(rangeParts[1].Trim(), prop.PropertyType);condition Expression.AndAlso(Expression.GreaterThanOrEqual(member, lower),Expression.LessThanOrEqual(member, upper));}break;case in:// value 格式1,2,3最多取 50 个防止 OR 链过长var inValues filter.Value?.Split(,).Take(50).Select(v ParseConstant(v.Trim(), prop.PropertyType)).ToList() ?? [];if (inValues.Count 0){condition inValues.Select(v (Expression)Expression.Equal(member, v)).Aggregate(Expression.OrElse);}break;case isnull:condition Expression.Equal(member, Expression.Constant(null, prop.PropertyType));break;case isnotnull:condition Expression.NotEqual(member, Expression.Constant(null, prop.PropertyType));break;}if (condition null) continue;var lambda Expression.LambdaFuncT, bool(condition, param);query query.Where(lambda);}return query;}// 把字符串值转成对应类型的常量表达式private static ConstantExpression ParseConstant(string? value, Type targetType){var underlyingType Nullable.GetUnderlyingType(targetType) ?? targetType;if (value null)return Expression.Constant(null, targetType);var converted Convert.ChangeType(value, underlyingType);return Expression.Constant(converted, targetType);}contains/startswith/endswith应对字符串gt/lt/between应对对数值和日期。类型不匹配时会抛异常生产代码里可以在这里加 try-catch捕获后根据情况进行处理。动态返回字段有时候列表页只需要id和name详情页才需要全量字段。与其写两个接口不如让前端自己说想要哪些字段我经历的项目都是后端定义好给前端哈不是前段自己拿前段自己也不想拿。思路是查出完整的实体然后用反射把指定字段打包成字典返回JSON 序列化后就只有这些字段。public static class FieldSelectorExtensions{public static IDictionarystring, object? SelectFieldsT(this T obj,IEnumerablestring fields){var result new Dictionarystring, object?(StringComparer.OrdinalIgnoreCase);var props typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);foreach (var fieldName in fields){var prop props.FirstOrDefault(p p.Name.Equals(fieldName, StringComparison.OrdinalIgnoreCase));if (prop ! null)result[prop.Name] prop.GetValue(obj);}return result;}public static IEnumerableIDictionarystring, object? SelectFieldsT(this IEnumerableT items,string? fields){if (string.IsNullOrWhiteSpace(fields)){var allProps typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(p p.Name);return items.Select(item item.SelectFields(allProps));}var fieldList fields.Split(,, StringSplitOptions.RemoveEmptyEntries).Select(f f.Trim());return items.Select(item item.SelectFields(fieldList));}}安全性字段白名单动态过滤和动态返回字段功能很方便但不是所有字段都该暴露出去比如密码、证件号、客户姓名这类。用一个自定义 Attribute 来标记哪些字段允许外部操作[AttributeUsage(AttributeTargets.Property)]public class FilterableAttribute : Attribute { }public class Product{public int Id { get; set; }[Filterable]public string Name { get; set; } string.Empty;[Filterable]public decimal Price { get; set; }[Filterable]public int Stock { get; set; }// 不加 [Filterable]外部无法通过 filters 参数过滤这个字段public string InternalRemark { get; set; } string.Empty;}ApplyFilters里已经加了这个检查prop.IsDefined(typeof(FilterableAttribute), false)找到属性之后会先验证标记没有就跳过。也可以反着来设计加一个FilterIgnore特性检查的地方做相应的调整。接到 Controller 里有了这些扩展方法Controller 里的逻辑就很平[HttpGet]public async TaskActionResult GetProducts([FromQuery] QueryParameters parameters){var query _context.Products.AsQueryable();// 动态过滤if (parameters.Filters.Count 0)query query.ApplyFilters(parameters.Filters);// 先算总数必须在分页之前var totalRecords await query.CountAsync();// 排序 分页var items await query.ApplySort(parameters.SortBy).ApplyPagination(parameters.PageNumber, parameters.PageSize).Select(p new ProductDto{Id p.Id,Name p.Name,Price p.Price,Stock p.Stock}).ToListAsync();// 按需返回字段var data items.SelectFields(parameters.Fields).ToList();return Ok(new{data,pageNumber parameters.PageNumber,pageSize parameters.PageSize,totalRecords,totalPages (int)Math.Ceiling(totalRecords / (double)parameters.PageSize),hasNextPage parameters.PageNumber (int)Math.Ceiling(totalRecords / (double)parameters.PageSize),hasPreviousPage parameters.PageNumber 1});}前端请求示例# 查价格在 100-500 之间、名字包含手机只返回 id 和 name按价格升序GET /api/products?filters[0].fieldpricefilters[0].opbetweenfilters[0].value100,500filters[1].fieldnamefilters[1].opcontainsfilters[1].value手机fieldsid,namesortByprice ascpageNumber1pageSize20返回结果{data: [{ Id: 1, Name: iPhone 16 },{ Id: 2, Name: 小米 15 }],pageNumber: 1,pageSize: 20,totalRecords: 2,totalPages: 1,hasNextPage: false,hasPreviousPage: false}
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2492901.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!