Search code examples
c#asp.net-web-apiodata

Use OData FilterQueryValidator to enforce criteria like "Must Include", "Should Include"


I need to check and validate OData filter query for must include property and value.

Ex: Lets say for an incoming filter query,

  • Must include "RegionID" in the filter, and
  • "RegionID" must contain the value 5

(Of course "RegionID" and value "5" needs to be dynamically changeable, So the same filter can be used to check for other properties and values and even multiple properties and multiple values as well)

What I've been trying so far is to use a custom FilterQueryValidator to validate the above scenario (as mentioned here Security Guidance for ASP.NET Web API 2 OData). But still cannot figure out how to do it.

So my question are,

  1. Is it possible to do this using FilterQueryValidator?
  2. Is so then how can i do this using FilterQueryValidator? (and if possible can you please provide me with some sample code as a starting point).
  3. If this isn't possible then how can i archive this?

About project

  • WebAPI 2 and OData v3 (both are unchangeable)

Thanks.

Update

As per Fan Ouyang answer i ended up overriding both Validate and ValidateSingleValuePropertyAccessNode to check the required parameters


Solution

  • http://blogs.msdn.com/b/webdev/archive/2013/02/06/protect-your-queryable-api-with-validation-feature-in-asp-net-web-api-odata.aspx

    Scenario 8: How to customize default validation logic for $skip, $top, $orderby, $filter

    In ValidateSingleValuePropertyAccessNode method Check the property name through propertyAccessNode.Property.Name, check the operator through binaryOperatorNode.OperatorKind

    var binaryOperatorNode = propertyAccessNode.Source as BinaryOperatorNode
    

    Check the right side 5 at binaryOperatorNode.Right as ConstantNode.

    I think there is enough hook and public method to achieve this, code is clear https://github.com/OData/WebApi/blob/master/OData/src/System.Web.Http.OData/OData/Query/Validators/FilterQueryValidator.cs