Custom Validation in ASP.NET Web API

We should never trust any input to our applications, so we need validate all of them

The problem is that we want our validation to be performed in the API layer, and not make the clients responsible for implementing their own validation. In other words, we need to do the following:

  1. Validate all incoming requests.
  2. Return any validation error messages to the calling clients.


Validating the Request

public class ValidateModelStateFilter : ActionFilterAttribute
public override void OnActionExecuting(HttpActionContext actionContext)
if (!actionContext.ModelState.IsValid)
var request = actionContext.ActionArguments.Select(x => x.Value).FirstOrDefault();
var response = new ApiResponse<object>()
Success = false,
ErrorCode = “400”,
ErrorMessage = string.Join(“,”, actionContext.ModelState.Values.SelectMany(e => e.Errors.Select(er => er.ErrorMessage))),
Results = null
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, response);

in WebApiConfig.cs

config.Filters.Add(new ValidateModelStateFilter());

In model object:

public int? ProductVersionId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int? Type { get; set; }
public string FormatNumber { get; set; }
public string DefaultValue { get; set; }

Testing the Validation
We can see the result like this when the value request is invalid:

Reponse body:

“Success”: false,
“Results”: null,
“ErrorCode”: “400”,
“ErrorMessage”: “The Name field is required.,The Description field is required.”



One thought on “Custom Validation in ASP.NET Web API

Leave a Reply

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

You are commenting using your 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