Validation in WCF Web Api

I’ve been working on a RESTful api recently using WCF Web Api (Preview 6). It’s like a breath of fresh air to work on something so uncluttered, I’ve come from working on a complex, multi-technology, web site. Working with a RESTful api is just so simple, but it presents its own challenges which I am overcoming one by one. One such challenge is validating the resources coming in via a POST method. I found a very useful answer on stack overflow which got me some of the way there. I spent some time refining it a bit and eventually came up with this …

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net.Http;
using ByBox.WebApi.HttpResponseMessages;
using Microsoft.ApplicationServer.Http.Dispatcher;

namespace WhateverYouWant
{
public class ValidationHandler<TResource> : HttpOperationHandler<TResource, HttpRequestMessage, HttpRequestMessage>
{
public ValidationHandler() : base("response") { }

        protected override HttpRequestMessage OnHandle(TResource model, HttpRequestMessage requestMessage)
        {
            var results = new List<ValidationResult>();
            var context = new ValidationContext(model, null, null);
            Validator.TryValidateObject(model, context, results, true);

            if (results.Count == 0)
            {
                return requestMessage;
            }

            var errorMessages = results.Select(x => x.ErrorMessage).ToArray();

            var mediaType = requestMessage.Headers.Accept.FirstOrDefault();
            var response = new RestValidationFailure(errorMessages);
            if (mediaType != null)
            {
                response.Content = new ObjectContent(typeof(string[]), errorMessages, mediaType);
            }
            throw new HttpResponseException(response);
        }
    }
}

What I added to the answer on stack overflow was the ability to return a list of error messages in both the headers and the body of the response. The list of errors in the body are sent in the format the browser will “accept”. This helps keep everything simple on the client side. I have only checked if it works for xml and json. For the sake of completeness I have included a version of my RestValidationFailure class.

using System.Net.Http;

namespace WhateverYouWant
{
    public class RestValidationFailure : HttpResponseMessage
    {
        public RestValidationFailure(string[] errorMessages)
        {
            StatusCode = HttpStatusCode.BadRequest;
            foreach (var errorMessage in errorMessages)
            {
                Headers.Add("X-Validation-Error", errorMessage);
            }
        }
    }
}
Advertisements

One response to “Validation in WCF Web Api

  1. Pingback: antony_scott » Blog Archive » ASP.NET Web Api Validation with Data Annotations

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