Skip to content

Validating inputs for PATCH requests in ASP.NET WebAPI

May 10, 2013

In ASP.NET WebAPI (with its recent OData additions) there is good support for HTTP PATCH requests via the Delta<T> class. I won’t bother reproducing a tutorial here since there’s already a good one online.

The only problem with the PATCH support and tutorial is that there is no guidance on how to validate the model once you’ve accepted the partially updated data. So here’s what I came up with to validate the model once we’ve called Patch:

public HttpResponseMessage Patch(Guid id, Delta<TenantData> data)
{
    var tenant = this.TenantRepository.Get(id);
    if (tenant == null) return Request.CreateResponse(HttpStatusCode.NotFound);

    data.Patch(tenant);

    // this is where we do the validation on the model after we've
    // merged in the patch values
    var svc = this.Configuration.Services;
    var validator = svc.GetBodyModelValidator();
    var ad = svc.GetActionSelector().SelectAction(this.ControllerContext);
    var ac = new HttpActionContext(this.ControllerContext, ad);
    var mp = svc.GetModelMetadataProvider();
    if (!validator.Validate(tenant, typeof(TenantData), mp, ac, "data"))
    {
        // validation failed, so return our error and pass along the 
        // ModelState from the action context (which is a different
        // instance than this.ModelState)
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, 
                                           ac.ModelState);
    }

    this.TenantRepository.SaveChanges();

    return Request.CreateResponse(HttpStatusCode.OK, tenant);
}

In essence, I needed to manually trigger validation that normally happens during model binding. I wish there was a nice API built-in for this, but alas there is not.

One Comment leave one →
  1. vijay permalink
    December 3, 2015 12:38 am

    Good one..it was helpful

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: