c# - .net 5 - 将字符串查询参数绑定到字典
问题描述
我们最近在查询参数中添加了对运算符的支持,例如:
/api/books?price[gt]=10
/api/books?price[eq]=10 or /api/books?price=10
...
以前的行为只允许:
/api/books?price=10
为了实现上述过滤能力,我们在请求模型中添加了一个字典字段:
public class BookRequestModel
{
[FromQuery]
public int Price { get; set; }
[FromQuery(Name = "Price")]
public Dictionary<string, int> PriceOperators { get; set; }
}
现在,这工作正常,但它需要我们为每个查询参数添加两个查询参数属性。现在可以在模型绑定之前动态更新查询参数键并附加“[eq]”。例如,如果用户提出以下请求:
/api/books?price=10
它更新为
/api/books?price[eq]=10
在模型绑定步骤之前。这样,对于每个查询参数,我们只需要请求模型中的一个属性:
public class BookRequestModel
{
[FromQuery]
public Dictionary<string, int> Price { get; set; }
}
我尝试更改中间件中的查询参数键,但context.Request.Query
它是只读的并且不允许更新键。
解决方案
推荐阅读
- excel - 如何根据信息范围输出日期?
- java - JWT 令牌在 .NET 上缺少部分标头,但在 Java 中没有
- raspberry-pi - pyqt5 GUI 在 raspberry pi 中与在带有 groupbox 的 QtCreator 中看起来不同
- oauth-2.0 - OAuth 2.0,如何让发起者知道权限是否被授予/拒绝?
- html - 在 React js 中悬停时更改单个锚链接的颜色
- c++ - 多图的迭代器值不变 - C++
- r - 如何在数据框中的一列值下生成随机均匀分布,而不必为所述列中的每个值重复?
- git - 如何在解决冲突的同时将一个分支合并到另一个分支
- valgrind - 几个小时后 Valgrind 停止
- laravel - 错误调用未定义函数 App\Http\Controllers\Admin\get_option()