IQueryCollection.ToList() 不需要地组合值

问题描述 投票:0回答:1

我的项目使用了两个库:

  • Swashbuckle.ASPNetCore
  • FluentValidation

我正在编写一个验证器拦截器来做一些额外的检查,这些检查需要与验证器分开:

MyModelValidator : AbstractValidator<MyModel>

public class MyModel
{
    public string City { get; set; }
    public List<string> Date { get; set; }
}

public class PrefixValidatorInterceptor : IValidatorInterceptor {
    public IValidationContext BeforeAspNetValidation(ActionContext acionContext, IValidationContext commonContext) {...}
}

到达

BeforeAspNetValidation
函数的对象是
MyModel
对象,例如这个请求的两个值的列表:http://localhost:{{port}}/api/endpoint?City=New约克&日期=02-05-2020&日期=07-27-2021

commonContext.InstanceToValidate.City = "New York"
commonContext.InstanceToValidate.Date[0] = "02-05-2020"
commonContext.InstanceToValidate.Date[1] = "07-27-2021"

现在我想将这个对象存储为字典/列表来验证它

List<KeyValuePair<string, StringValues>> getRequestValues = actionContext.HttpContext.Request.Query.ToList();

但这会将值与逗号分隔符结合起来。

getRequestValues[0] = { "City", "New York" }
getRequestValues[1] = { "Date", "02-05-2020,07-27-2021" }

相反,我希望它看起来像这样:

getRequestValues[0] = { "City", "New York" }
getRequestValues[1] = { "Date", "02-05-2020" }
getRequestValues[2] = { "Date", "07-27-2021" }

或者,仅包含值的列表也是可以接受的:

anotherList[0] = "New York"
anotherList[1] = "02-05-2020"
anotherList[2] = "07-27-2021"

您不能只在逗号字符上拆分字符串,因为值本身可能包含逗号,因此该选项似乎不可行。

我知道

HttpContext.Request.Query
IQueryCollection
)利用了
StringValues : IList<string>
类型 因为调用
.ToList()
的值是 .NET Core 3.1 Enummerable 类的一部分,因此无法真正更改。

我想到的一个解决方案是对设置的对象使用反射

IValidationContext.InstanceToValidate
并遍历其所有字段并手动构建
List<>
.

有更好的方法吗?

我试过

.ToList();
.ToDictionary();
但两者都会将日期值与逗号分隔符结合起来。

c# ienumerable iqueryable swashbuckle.aspnetcore
1个回答
0
投票

最后将执行以下操作:

var getRequestValues = new List<string>();
foreach (var field in context.HttpContext.Request.Query)
{
    foreach (var value in field.Value)
    {
        getRequestValues.Add(value);
    }
}

.Query
是一个
IQueryCollection
和可循环的,从它出来的
.Value
是类型
StringValues
,它实现了
IList<string>
,所以也是可循环的。

这行得通,不需要额外的思考。

© www.soinside.com 2019 - 2024. All rights reserved.