首页 > 解决方案 > .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它是只读的并且不允许更新键。

标签: c#asp.net.net

解决方案


推荐阅读