我有一个安静的webapi,我想支持一个查询参数,用于搜索?q=
我想做的是使用delegatingHandler来更改响应 基本上为每种类型的资源创建一个QueryHandler
BaseQueryHandler方法看起来像这样
HttpResponseMessage IQueryHandler.Query(HttpResponseMessage response, string query)
{
httpResponse = response;
T content;
if (response.TryGetContentValue(out content))
{
response = Request.CreateResponse(Query(content, query));
}
return response;
}
具体的QueryHandler如此
public override Organization Query(Organization content, string query)
{
query = query.ToLower();
var organization = content.ChildOrganizations?.Where(o => o.Name.ToLower().Contains(query));
return
}
我一定会看看OData。
到目前为止我所做的是实现我的QueryHandler,然后使用扩展方法搜索字段和值的对象
public static IEnumerable<T> LikeOr<T>(this IEnumerable<T> source, string columnName, string searchTerm)
{
IEnumerable<string> words =
searchTerm.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries).Where(x => x.Length > 1);
var sb = new StringBuilder();
for (int i = 0; i < words.Count(); i++)
{
if (i != 0)
sb.Append(" || ");
sb.Append(words.First().IsNumeric() ? $"{columnName} = @{i}" : $"{columnName}.Contains(@{i})");
}
var intSearch = 0;
if (int.TryParse(words.First(), out intSearch))
return source.Where(sb.ToString(), intSearch);
return source.Where(sb.ToString(), words.ToArray());
}
然后在我的具体searcHandler实现中使用它,如此
public override IEnumerable<Organization> Search(IEnumerable<Organization> content, string query)
{
var searchTerm = query.Split(':');
var field = searchTerm[0];
var term = searchTerm[1];
var entitites = content.LikeOr(field, term);
return entitites;
}
(实际上在另一个答案中找到了这个动态.Linq(不记得URL,当我重新绑定时会更新,给予适当的信用)
你们中有人有更好的方法吗?
通常你会在所有动作上都有正确的查询参数,我不想那样:)