5

I have a web api backend project on which I would like to bring the following feature :

Prevent a object property to be use in a query if it's used with an OR operator.

Example :

This is my exposed object :

public class Session
{
 public string Name {get;set;}
 public string Number {get;set;}
}

So the api consumer could have the possibility to do those queries :

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'

However, if he do the following query :

mydomain/api/data/sessions?$filter=Name eq 'name1'or Number eq 'number1'

He must be rejected, because the Number field cannot be combined to an OR operator. Actually he can do this query, but I am looking for a proper way to reject this query. I was thinking to override the EnableQueryAttribute of oData and more precisely its method :

[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.
    }
}
user2443476
  • 1,935
  • 9
  • 37
  • 66
  • 1
    Did you manage to solve this in the end? – gorillapower Oct 14 '17 at 10:00
  • Maybe this can help https://stackoverflow.com/q/52040901/3797799 – colinD May 16 '20 at 13:40
  • Since it appears you want to analyze the whole statement and then make a call whether you want to allow the filter altogether you might want to look at [parsing it](https://stackoverflow.com/a/60188694/12339804) – timur May 20 '20 at 15:29

0 Answers0