Search code examples
asp.net-mvcvalidationodataasp.net-web-api

ASP.NET Web Api OData: How to validate Delta<Entity>?


I have a Validation Framework set up to automatically validate parameters of Web Api action methods (including OData action methods). However, this does not work for PATCH requests that store the changed properties in a Delta<Entity> type.

I've done some digging around and, as you can see in the ASP.NET source code of Delta, it has the NonValidatingParameterBinding attribute, which means that Delta's are not subjected to validation.

Now an obvious solution would be to apply the delta and then perform manual validation of the resulting entity.

But are there other solutions that do not require applying the patch? Ideally it should happen automatically before the action method is called...

Thanks.


Solution

  • It was an explicit design decision to not validate Delta<Entity>. Reason being, a Delta<Entity> is only a partial entity and by definition could be invalid. As you have guessed, the proper approach is to validate the entity after the Delta<TEntity> is applied on top of it.

    Sample code,

    public void Patch(Delta<Customer> delta)
    {
        Customer c = new Customer();
        delta.Patch(c);
    
        Validate(c, typeof(Customer));
    }
    
    private void Validate(object model, Type type)
    {
        var validator = Configuration.Services.GetBodyModelValidator();
        var metadataProvider = Configuration.Services.GetModelMetadataProvider();
    
        HttpActionContext actionContext = new HttpActionContext(ControllerContext, Request.GetActionDescriptor());
    
        if (!validator.Validate(model, type, metadataProvider, actionContext, String.Empty))
        {
            throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState));
        }
    }
    

    Complete sample here.