ASP.NET Web Api复杂的查询参数

Mat*_*ero 5 c# asp.net asp.net-web-api

我有一个Web Api端点,目前这样称为:

http://api.example.com/scenes?creationDate=1440091949
Run Code Online (Sandbox Code Playgroud)

我正在尝试支持更复杂的查询,例如:

http://api.example.com/scenes?creationDate.lt=1440091949
Run Code Online (Sandbox Code Playgroud)

注意.lt后缀.这将让用户列出所有的场景中,creationDate小于(LT)比1440091949.

为此,我必须创建自己的映射器函数,它将每个查询参数映射到查询模型的属性,并将每个查询操作(lt,gt,eq等等)存储在操作字典中:

protected QueryData MapToQueryData(IEnumerable<KeyValuePair<string, string>> queryParameters)
{
     QueryData queryData = new QueryData();

     foreach(var queryParam in queryParameters)
     {
          string[] segments = queryParam.Key.Split('.'); // ["creationDate", "lt"]
          if(!segments.Any()) continue;

          PropertyInfo queryProperty = _reflection.Properties.GetProperty<QueryData>(segments.First()); // "CreationDate" Property
          if(queryProperty == null) continue;

          object value = _reflection.Conversion.ConvertTo(queryParam.Value, property.PropertyType); // Convert 1440091949 to long
          if(value == null) continue;

          _reflection.Properties.SetPropertyValue(queryData, property, value); // Set queryData.CreationDate = 1440091949

          if(segments.Length < 2) continue;

          PropertyInfo mapProperty = _reflection.Properties.GetPropertiesWithAttribute<QueryData, OperationMapAttribute>().FirstOrDefault(); // Identify Property annotated with [OperationMap]
          if(mapProperty == null) continue;

          Dictionary<string, string> operationMap = _reflection.Properties.GetPropertyValue(queryData, mapProperty) as Dictionary<string, string>(); // Get dictionary from Map property
          if(operationMap == null) continue;

          if(!operationMap.ContainsKey(property.Name))
                 operationMap.Add(property.Name, segments.Last()); // "creationDate" -> "lt"
          else
                 operationMap[property.Name] = segments.Last();

          _reflection.Properties.SetPropertyValue(queryData, mapProperty, operationMap); // Set Map property of QueryData to the updated dictionary
     }

     return queryData;
}
Run Code Online (Sandbox Code Playgroud)

我知道如果一个人决定使用该[FromUri]属性,ASP.NET Web Api提供了一个自动映射,但是如果我有简单的查询参数creationDate=1440091949,如果我发送一个查询参数,如果不行,那就行了creationDate.lt=1440091949.

在Web APi引擎中是否有内置的东西来处理这些类型的查询参数?我在很多Web服务上看过它们,所以它们在订购或执行复杂查询时非常常见.

小智 5

您是否尝试过使用OData查询语法之类的东西?

http://blogs.msdn.com/b/martinkearn/archive/2015/03/10/using-odata-query-syntax-with-web-api.aspx

从上述......

什么是OData查询语法?

OData查询语法是使用预定义语法查询RESTful API的标准方法,该语法允许调用客户端定义排序顺序,过滤参数和返回的数据页面.

完整语法可以在OData Version 4.0 Part 2规范的第5节中找到,但这里有一些如何使用语法的简单示例:

  • .../host/service/Products?$ filter = Name eq'Milk':返回名称等于'Milk'的所有产品
  • .../host/service/Products?$ filter = Name eq'Milk'和Price lt 2.55:返回名称等于'Milk'并且价格低于2.55的所有产品
  • .../host/service/Products?$ top = 10&$ skip10:返回项目11> 21.$ top系统查询选项请求查询的集合中的项目数包含在结果中.$ skip查询选项请求查询集合中要跳过但未包含在结果中的项目数
  • .../host/service/Products?$ orderby = Name desc,Id:按降序返回按名称排序的所有产品,然后按ID排序
  • .../host/service/Products?$ filter = Enabled eq true:返回Enabled字段(布尔值)为true的所有产品
  • .../host/service/Products?$ filter = substringof('Martin',Name):返回名称字段包含文本Martin的所有产品

如何在ASP.net Web API中使用OData查询语法?

事情变得非常棒 - 超级,非常容易更改常规Web API控制器以支持OData查询语法 - 一旦你知道如何做到这一点,你就永远不会这样做!

如果我们假设我们从常规Web API项目(文件>新建项目> ASP.net Web应用程序> Web API)开始,您首先需要添加一个脚手架控制器,您可以按照以下步骤操作:

  1. 添加一个模型类(我使用典型的'Person'类,包括Id,名字,姓氏,年龄等)
  2. 使用Entity Framework> Model = Person右键单击'controllers'文件夹> Add> New Scaffolded item> Web API 2 Controller with actions

注意:您无需选择"Web API 2 OData Controller ..."选项,您可以将查询语法添加到任何控制器

一旦你设置了你的控制器,你应该得到一个简单的控制器,它有一个默认的GET动作,看起来有点像这样:

// GET: api/People
public IQueryable<Person> GetPeople()
{
    return db.People;
}
Run Code Online (Sandbox Code Playgroud)

此操作将简单地返回数据库"人员"表中的所有行,无法进行过滤,排序等.要添加完整的OData查询支持,您需要进行一些更改:

  1. 通过nugget添加Microsoft.Aspnet.OData包...只需将其弹出到"包管理器控制台"中:Install-Package Microsoft.AspNet.Odata
  2. 使用以下语句添加:使用System.Web.OData;
  3. 将[EnableQueryAttribute]属性添加到GetPeople操作中.
  4. 添加AsQueryable(); 到你的返回行所以它看起来像这样:return db.People.AsQueryable();

您完成的代码将如下所示:

// GET: api/People
[EnableQueryAttribute]
public IQueryable<Person> GetPeople()
{
    return db.People.AsQueryable();
}
Run Code Online (Sandbox Code Playgroud)

这就是它的全部!....现在你有了这个设置,你可以使用完整的OData语法来查询排序等,而无需任何额外的代码.