我有一个web api后端项目,我想在其上提供以下功能:
如果对象属性与OR运算符一起使用,则阻止在查询中使用该对象属性。
示例:
这是我暴露的对象:
public class Session
{
public string Name {get;set;}
public string Number {get;set;}
}
因此api消费者可以进行这些查询:
mydomain/api/data/sessions?$filter=Name eq 'name1'
mydomain/api/data/sessions?$filter=Number eq 'number1'
mydomain/api/data/sessions?$filter=Name eq 'name1'and Number eq 'number1'
但是,如果他执行以下查询:
mydomain/api/data/sessions?$filter=Name eq 'name1'or Number eq 'number1'
必须拒绝他,因为Number字段不能合并到OR运算符。 实际上他可以执行此查询,但我正在寻找一种拒绝此查询的正确方法。我想要覆盖oData的EnableQueryAttribute,更确切地说是它的方法:
[RoutePrefix("api/directory")]
public class SessionController : ApiController
{
[HttpGet]
[Route("sessions")]
[CheckQueryAttribute]
public IQueryable<Session> Get()
{
List<Session> list = new List<Session>();
list.Add(new Session { Name = "name 1", Number = "place 1" });
list.Add(new Session { Name = "name 2", Number = "place 2" });
list.Add(new Session { Name = "name 3", Number = "place 3" });
return list.AsQueryable();
}
}
public class CheckQueryAttribute : EnableQueryAttribute
{
public override IQueryable ApplyQuery(IQueryable queryable, ODataQueryOptions queryOptions)
{
// I am thinking to parse the query object here to check if the Number property is combined with an or operator
// but I don't know how to do it, and more important I am not sure if it's the right way.
}
}