在 ASP.NET Web API OData 中利用 Queryable API 进行验证

  • 2013-02-27
  • 本文字数:855 字

    阅读完需:约 3 分钟

ASP.NET Web API OData 中,可以利用 Queryable API 为特殊操作启用 OData 查询语法。如下所示:

[Queryable]
public IQueryable Get(int projectId)

然而,如果要向组织外部公开可查询的操作,可以利用查询验证添加一个保护层以保护我们的服务。微软的程序经理 Hongmei Ge 近日介绍了几种在 Queryable API 中添加验证的场景。

Hongmei 指出的第一个场景是,使用 AllowedQueryOptions 属性,只允许包含 $top 和 $skip 的查询。如下所示:

[Queryable(AllowedQueryOptions = AllowedQueryOptions.Skip | AllowedQueryOptions.Top)]
public IQueryable Get(int projectId)

还可以使用 MaxTop 和 MaxSkip 属性将 $top 和 $skip 的最大值限制在 100 和 200:

[Queryable(MaxTop = 100)]
public IQueryable Get(int projectId)

[Queryable(MaxSkip = 200)]
public IQueryable Get(int projectId)

利用 AllowedOrderByProperties,可以将结果按 Id 属性排序,因为按其他属性排序可能会很慢:

[Queryable(AllowedOrderByProperties = “Id”)]
public IQueryable Get(int projectId)

如果允许客户端在 $filter 内使用相等比较,应该使用 AllowedLogicalOperators 对其进行验证:

[Queryable(AllowedLogicalOperators = AllowedLogicalOperators.Equal)]
public IQueryable Get(int projectId)

将 AllowedArithmeticOperators 设置为 None,就可以关闭 $filter 中的算术操作:

[Queryable(AllowedArithmeticOperators = AllowedArithmeticOperators.None)]
public IQueryable Get(int projectId)

你还可以使用 AllowedFunctions 属性来限制 $filter 中的函数使用:

[Queryable(AllowedFunctions = AllowedFunctions.StartsWith)]
public IQueryable Get(int projectId)

上面的代码意味着只能在 $filter 中使用 StartsWith 函数。

Hongmei 还演示了高级场景中的查询验证,如为 $skip、$top、$orderby、$filter 自定义默认验证逻辑,以及使用 ODataQueryOptions 来验证查询。

查看英文原文 Applying Validation for Queryable API in ASP.NET Web API OData