Server Side Validation for Request in Web API

Posted: August 30, 2016 by Sagar Wasule in Asp.Net, C-Sharp, Programming Concepts, Web API
Tags: , , , , ,


Validation are utmost important part of a software product. It is important to validate the data that is going into the system at each and every layer. By each and every layer I mean it is important to have validation in place on client side, server-side and even database level.

Many a times we check for the actual data and validate the request. Here in this article I will explain how to validate our request on a API layer using custom generic method instead of validating on each method which we have written in our API. For this we will be creating a custom Action Filter and use it in combination with Data Annotation which will be our validation rules.

Step 1

Sample Class which uses Data Annotation:

These Data Annotation will work in validating the request received.

public class LoginRequest


    [Required (ErrorMessage = "Email is required")]

    public string Email { get; set; }

    [Required(ErrorMessage = "Email is required")]

    public string Password { get; set; }



This Required is a validation Attribute present in System.ComponentModel.DataAnnotations which check whether the Property has data or not. In the similar way we can create our custom Validation Attribute in order to check the value in request object.

Some other types of validation that we can handle are,

Types of Validation

Here we define the various types of validation that we can be use in our application. These are as follows:

  1. Required entry: It ensures the required field. The user cannot skip the entry.
  2. Compare Value: It ensures that the comparison of the user’s entry with the constant value or against the value of another constant or a specific data type. We use the comparison operator like equal, greater than, less than.
  3. Range checking: It checks the range of the input values with the minimum and maximum range that is required for the input value. We can use the range checker with the pairs of numbers, dates and alphabetic characters.
  4. Pattern matching: It is used for checking the pattern of an input value that specifies the sequence of characters.
  5. Remote: It is used for checking whether the value exists on the server-side.


Step 2

Model Validation Custom Action Filter:

This Action Filter will be used to validate the Model State globally on API Layer.

public class ValidateModelStateAttribute : ActionFilterAttribute
        public override void OnActionExecuting(HttpActionContext actionContext)
            if (!actionContext.ModelState.IsValid)
                string errMessage = string.Empty;
                foreach (ModelState modelState in actionContext.ModelState.Values)
                    foreach (ModelError error in modelState.Errors)
                        errMessage += "Error Message : " + error.ErrorMessage;
                actionContext.Response = 
                    actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, errMessage);

Ref Url :

Step 3

Register the “ValidateModelStateAttribute” to the API in WebAPIConfig.cs

public static class WebApiConfig
        public static void Register(HttpConfiguration config)
            //Server Side Model Validation
            config.Filters.Add(new ValidateModelStateAttribute());
            // Web API routes

                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                    = IncludeErrorDetailPolicy.Always;

With this approach we can make sure that request is validated easily on the API Level using a simple Global Action Filter.

Let me know if you have any queries or in case you have other better approach lets discuss in the comments below.

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 )

Google+ photo

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


Connecting to %s