Introduction

This article explains the Content Validation in the Web API. Here we need to install the Test Client for ASP.NET Web API. We install this package from the NuGet Package Manager.

Use the following procedure to create a sample application.

Step 1

First we create an Web API application as in the following:

Step 2

Create a Model class:

Add the following code:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Linq;
  5. using System.Web;
  6. namespace ContentValidationAPI.Models
  7. {
  8. public class Product
  9. {
  10. [Key]
  11. public int Prd_Id { get; set; }
  12. [Required]
  13. public string Prd_Name { get; set; }
  14. public string Prd_Description { get; set; }
  15. [Range(1, 1000)]
  16. public int Prd_Key { get; set; }
  17. public bool Prd_IsObsolete { get; set; }
  18. }
  19. }

Step 3

Now we add a Scaffold Web API controller as in the following:

That will create two files in your project.

Step 4

Now install the Test Client for ASP.NET Web API.

After installing this package we can see in the "HelpPage/Views/Help/DisplayTemplate/" path theree files added "TestClientDialogs.cshtml", "TestClientReferences.cshtml", and "TextSample.cshtml".

Step 5

Execute the application as in the following:

image..

Click on "API"; it will then display the Products API.

Execute application

Now click on the "Post API/Products"

and then click on the "TestAPI" button that is displayed in the lower-right corner.

Post APi Product

Now change the Body code as in the following:

{
"Prd_Id": 1,

"Prd_Description": "sample string 3",
"Prd_Key":-4,
"Prd_IsObsolete": false
}

And click on the "Send" button, it will then display an error message with validation.

Error for POST

If we again change the code depend on the validation such as:

{
"Prd_Id": 1,
"Prd_Name": "Product 1",
"Prd_Description": "Description of Product 1",
"Prd_Key": 4,
"Prd_IsObsolete": true
}

Then it displays the "Ok" message.

Response for POST APi

Now click on the "PUT API/Products/{id}"; it will then display like this:

Put API Product

Now again click on the "TestAPI" button and enter the id and change the code like this:

{
"Prd_Id": 1,
"Prd_Name": "sample string 2",

"Prd_Key": 4,
"Prd_IsObsolete": false
}

Now click on the "Send" button; it will display an "Ok" message:

PUT Response

Now click on the Get API/Product/{id}; it will display like this:

Get API Product

Click on the "Send" button; it will display an "Ok" message as in the following:

Response for Get API