gpt4 book ai didi

c# - 在 MVC Core 中动态按查询字符串过滤?

转载 作者:太空宇宙 更新时间:2023-11-03 12:06:13 26 4
gpt4 key购买 nike

我有一个这样的get方法...

[HttpGet]
public async Task<ActionResult<IEnumerable<Customer>>> GetCustomers()
{
var queryString = HttpContext.Request.Query;
return await _context.Customers.Take(7).ToListAsync();
}

我想传入这样的查询字符串:

https://localhost:44315/api/customer?param1=1&param2=String Value

我想这样做而不必在我的参数列表中声明每个参数。例如

[HttpGet]
public async Task<ActionResult<IEnumerable<Customer>>> GetCustomers(int param1, string param2)
{
var queryString = HttpContext.Request.Query;
return await _context.Customers.Take(7).ToListAsync();
}

我想避免这样做,因为我的类有几十个参数。我知道您可以与 [FromQuery] Customer customer 进行绑定(bind),但我认为这不是我想要的。

有没有办法动态地做到这一点?

最佳答案

我最终做了这样的事情

   //GET: api/customer
[HttpGet]
public async Task<ActionResult<IEnumerable<Customer>>> GetCustomers()
{
var queryParams = HttpContext.Request.Query;
var collection = _context.Customers.FilterByQueryParams(queryParams);
return await Task.FromResult(collection.ToList());
}

然后在一个单独的类中

public static class DynamicFilterExtensionMethods
{
public static IEnumerable<T> FilterByQueryParams<T>(this IEnumerable<T> collection, IQueryCollection queryParams) where T : new()
{
var classType = typeof(T);
var propList = classType.GetProperties();
//accountNumber ==> accountNumber, AccountNumber ==> accountNumber
var props = new Dictionary<string, PropertyInfo>(propList.Select(x => new KeyValuePair<string, PropertyInfo>(Char.ToLowerInvariant(x.Name[0]) + x.Name.Substring(1), x)));

foreach (var param in queryParams) {
if (props.ContainsKey(param.Key)) {
var prop = props[param.Key];
if (prop.PropertyType.IsPrimitive) {
if (param.Value.Count == 1)
{
collection = collection.Where(x => prop.GetValue(x, null).ToString() == param.Value.First());
}
else {
var aggregate = new List<T>();
foreach (var value in param.Value) {
aggregate = aggregate.Union<T>(collection.Where(x => prop.GetValue(x, null).ToString() == value)).ToList();
}
collection = aggregate.AsEnumerable();
}
}
}
}

return collection;
}
}

这里还有很多工作要做,但我认为这是一个不错的开始。

关于c# - 在 MVC Core 中动态按查询字符串过滤?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54837426/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com