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:

[Required]
public int? ProductVersionId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
[Required]
public int? Type { get; set; }
public string FormatNumber { get; set; }
[Required]
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.”
}

 

Advertisements

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:

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