ASP.NET Web Api Validation with Data Annotations

I’ve recently moved a project over from WCF Web Api over to ASP.NET Web Api. In doing that I needed to re-implement my validation code. Thanks to the Api being a part of the MVC framework, things are much simpler now.

public class ValidationActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext context)
    {
        var modelState = context.ModelState;
        if (!modelState.IsValid)
        {
            dynamic errors = new JsonObject();
            foreach (var key in modelState.Keys)
            {
                var state = modelState[key];
                if (state.Errors.Any())
                {
                    errors[key] = state.Errors.First().ErrorMessage;
                }
            }

            context.Response = new HttpResponseMessage<JsonValue>(
                errors,
                HttpStatusCode.BadRequest);
        }
    }
}

All I need do now is decorate my models appropriately, for example …

public class TellAFriend
{
    [StringLength(100)]
    public string ToName { get; set; }

    [StringLength(100)]
    [Required]
    [RegularExpression(Regexes.EmailPattern, ErrorMessage = "Invalid email address")]
    public string ToEmailAddress { get; set; }
}

I will get a HTTP 400 response with a nice array of key/value pairs in the response body whenever a client sends me bad data.

{
    "ToEmailAddress": "Invalid email address"
}
About these ads

5 responses to “ASP.NET Web Api Validation with Data Annotations

  1. Pingback: antony_scott » Blog Archive » Hosting ASP.NET Web Api with IIS

  2. while trying to access this set of api with using php cURL it returns  likes this
    {ToEmailAddress: [ ]}

    Any Ideas why ? for the following code.

    $result=json_encode($web->api(‘TellAFriend’, array(
    ‘ToName’=>’John Doe’,
    ‘ToEmailAddress’=>’wrongemailaddreess”
    )));
    echo($result);

    • Sorry, it’s a bit difficult to say without more information. I suggest you ask a question on stackoverflow giving as much information as you can.

  3. What if the client asked for XML? Could you somehow make an anonymous class to hold the error information that could then be serialized by the framework into the format that was requested?

    • I’ve not tried using an anonymous class. I’ve since created an ApiError class and return the errors in that, so the content type negotiation of ASP.NET Web API should take care of how the client wants to receive the result.

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