使用.NET 6开发TodoList应用(14)——实现查询过滤
系列导航及源代码#
需求#
在查询请求中,还有一类常见的场景是过滤查询,也就是有限制条件的查询,落在数据库层面就是常用的Where
查询子句。实现起来也很简单。
目标#
实现查询过滤的功能
原理与思路#
查询过滤的请求有两种方式,一种是采用POST
方法,将查询条件放在请求体中,但是这种方式实际上和Restful的动词语义产生了矛盾,从Restful API成熟度模型的角度来说,还停留在Level 1阶段(仅知道地址,不符合动词语义),详情参考理查森成熟度模型;还有一种方法是采用GET
方法,将查询条件放在查询字符串里,我们将采用第二种方式来实现。
实现#
我们还是通过查询TodoItem
列表来演示查询过滤,和前面的文章一样,我们先来实现一个查询的Query
请求对象:
GetTodoItemsWithConditionQuery.cs
using AutoMapper;
using AutoMapper.QueryableExtensions;
using MediatR;
using TodoList.Application.Common.Interfaces;
using TodoList.Application.Common.Mappings;
using TodoList.Application.Common.Models;
using TodoList.Domain.Entities;
using TodoList.Domain.Enums;
namespace TodoList.Application.TodoItems.Queries.GetTodoItems;
public class GetTodoItemsWithConditionQuery : IRequest<PaginatedList<TodoItemDto>>
{
public Guid ListId { get; set; }
public bool? Done { get; set; }
public PriorityLevel? PriorityLevel { get; set; }
public int PageNumber { get; set; } = 1;
public int PageSize { get; set; } = 10;
}
public class GetTodoItemsWithConditionQueryHandler : IRequestHandler<GetTodoItemsWithConditionQuery, PaginatedList<TodoItemDto>>
{
private readonly IRepository<TodoItem> _repository;
private readonly IMapper _mapper;
public GetTodoItemsWithConditionQueryHandler(IRepository<TodoItem> repository, IMapper mapper)
{
_repository = repository;
_mapper = mapper;
}
public async Task<PaginatedList<TodoItemDto>> Handle(GetTodoItemsWithConditionQuery request, CancellationToken cancellationToken)
{
return await _repository
.GetAsQueryable(x => x.ListId == request.ListId
&& (!request.Done.HasValue || x.Done == request.Done)
&& (!request.PriorityLevel.HasValue || x.Priority == request.PriorityLevel))
.OrderBy(x => x.Title)
.ProjectTo<TodoItemDto>(_mapper.ConfigurationProvider)
.PaginatedListAsync(request.PageNumber, request.PageSize);
}
}
甚至为了结合之前讲的请求校验,我们可以在这里增加一个校验规则:
GetTodoItemValidator.cs
using FluentValidation;
namespace TodoList.Application.TodoItems.Queries.GetTodoItems;
public class GetTodoItemValidator : AbstractValidator<GetTodoItemsWithConditionQuery>
{
public GetTodoItemValidator()
{
RuleFor(x => x.ListId).NotEmpty().WithMessage("ListId is required.");
RuleFor(x => x.PageNumber).GreaterThanOrEqualTo(1).WithMessage("PageNumber at least greater than or equal to 1.");
RuleFor(x => x.PageSize).GreaterThanOrEqualTo(1).WithMessage("PageSize at least greater than or equal to 1.");
}
}
接下来在TodoItemController
中实现请求处理,我们直接修改上一篇讲分页的那个请求成如下(如果在上一篇的基础上新增Action的话,会导致路由的歧义):
TodoItemController.cs
// 省略其他...
[HttpGet]
public async Task<ApiResponse<PaginatedList<TodoItemDto>>> GetTodoItemsWithCondition([FromQuery] GetTodoItemsWithConditionQuery query)
{
return ApiResponse<PaginatedList<TodoItemDto>>.Success(await _mediator.Send(query));
}
验证#
启动Api
项目,执行创建TodoList
的请求:
请求仅携带Done
过滤条件时#
请求仅携带PriorityLevel
过滤条件时#
请求携带完整的过滤条件时#
请求参数不合法时#
总结#
对于查询过滤这个需求来说,实现起来还是很简单的,但是这里其实隐藏了一个很重要的问题:如果查询的参数太多,比如存在多个Guid
类型的字段过滤,URL的总长度是有可能超出浏览器或者服务器Host环境限制的,在这种情况下,我们是否还要坚持使用符合理查森成熟度模型Level 2的GET
请求呢?
关于这个问题的争论一直以来就没有停过,首先说我个人的结论:可以采用POST
的方式去变通,没必要为难自己(虽然这话肯定会引来Restful拥趸的嘲讽)。可是如果对成熟度有硬性的要求,我们如何实现?比较通用的解决方案是将一步GET
查询拆成两步GET
查询。但是更多的情况,是我认为如果出现了这种情况,就放弃Restful风格吧。
其实GraphQL才是王道。
参考资料#
作者:CODE4NOTHING
出处:https://www.cnblogs.com/code4nothing/p/build-todolist-14.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
欢迎转载,转载请注明出处
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库