Working With Test Client In ASP.NET Web API Help Page

As you all know, if you create a sample API project you will get a folder HelpPage in Areas. This is for adding the XML description to each controller and actions we use in our API. If you document it well, any one can understand your API, so that you don’t need to explain what your API will do and what would be the output. If you are new to HelpPage implementation in API, please see here: API help page controller action description in Web API. Here I am going to create a Web API with the help page descriptions in Visual Studio 2015. And once the project is ready I will install the WebApiTestClient package to my solution. I hope you will like this.

Please be noted that this package is not officially released by Microsoft. This is a prototype created by Yao – MSFT 

Download the source code

You can always download the source code here: API Test Client

Background

For the past few months, I had been working with API projects. Recently I was asked to create an application to test the API I created so that the testing team can test the API easily. Yes I agree that we have tools like Fiddler and Post Man for the same. Still we thought to create our own. As I started my development, I came to know about the package WebApiTestClient which does what we wanted. Finally we decided to stop developing the application and used this wonderful package. Here I am going to show you how can we use this.

Prerequisites

  • Visual Studio With Web API Installed

Things we are going to do:

The following are the tasks we are going to do.

  • Setting up database
  • Creating an Entity Framework
  • Creating API controller with the Model Created
  • Installing WebApiTestClient
  • Configuring WebApiTestClient
  • Testing WebApiTestClient

Setting up database

Here I am going to create a database which I created for my demo purposes, you can always create this database by running the queries mentioned here.

Create database

  1. USE[master]  
  2. GO  
  3. /****** Object: Database [TrialsDB] Script Date: 5/12/2016 10:56:41 AM ******/  
  4. CREATE DATABASE[TrialsDB]  
  5. CONTAINMENT = NONE  
  6. ON PRIMARY  
  7.     (NAME = N 'TrialsDB', FILENAME = N 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB.mdf'SIZE = 3072 KB, MAXSIZE = UNLIMITED, FILEGROWTH = 1024 KB)  
  8. LOG ON  
  9.     (NAME = N 'TrialsDB_log', FILENAME = N 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB_log.ldf'SIZE = 1024 KB, MAXSIZE = 2048 GB, FILEGROWTH = 10 % )  
  10. GO  
  11. ALTER DATABASE[TrialsDB] SET COMPATIBILITY_LEVEL = 110  
  12. GO  
  13. IF(1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))  
  14. begin  
  15. EXEC[TrialsDB].[dbo].[sp_fulltext_database] @action = 'enable'  
  16. end  
  17. GO  
  18. ALTER DATABASE[TrialsDB] SET ANSI_NULL_DEFAULT OFF  
  19. GO  
  20. ALTER DATABASE[TrialsDB] SET ANSI_NULLS OFF  
  21. GO  
  22. ALTER DATABASE[TrialsDB] SET ANSI_PADDING OFF  
  23. GO  
  24. ALTER DATABASE[TrialsDB] SET ANSI_WARNINGS OFF  
  25. GO  
  26. ALTER DATABASE[TrialsDB] SET ARITHABORT OFF  
  27. GO  
  28. ALTER DATABASE[TrialsDB] SET AUTO_CLOSE OFF  
  29. GO  
  30. ALTER DATABASE[TrialsDB] SET AUTO_CREATE_STATISTICS ON  
  31. GO  
  32. ALTER DATABASE[TrialsDB] SET AUTO_SHRINK OFF  
  33. GO  
  34. ALTER DATABASE[TrialsDB] SET AUTO_UPDATE_STATISTICS ON  
  35. GO  
  36. ALTER DATABASE[TrialsDB] SET CURSOR_CLOSE_ON_COMMIT OFF  
  37. GO  
  38. ALTER DATABASE[TrialsDB] SET CURSOR_DEFAULT GLOBAL  
  39. GO  
  40. ALTER DATABASE[TrialsDB] SET CONCAT_NULL_YIELDS_NULL OFF  
  41. GO  
  42. ALTER DATABASE[TrialsDB] SET NUMERIC_ROUNDABORT OFF  
  43. GO  
  44. ALTER DATABASE[TrialsDB] SET QUOTED_IDENTIFIER OFF  
  45. GO  
  46. ALTER DATABASE[TrialsDB] SET RECURSIVE_TRIGGERS OFF  
  47. GO  
  48. ALTER DATABASE[TrialsDB] SET DISABLE_BROKER  
  49. GO  
  50. ALTER DATABASE[TrialsDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF  
  51. GO  
  52. ALTER DATABASE[TrialsDB] SET DATE_CORRELATION_OPTIMIZATION OFF  
  53. GO  
  54. ALTER DATABASE[TrialsDB] SET TRUSTWORTHY OFF  
  55. GO  
  56. ALTER DATABASE[TrialsDB] SET ALLOW_SNAPSHOT_ISOLATION OFF  
  57. GO  
  58. ALTER DATABASE[TrialsDB] SET PARAMETERIZATION SIMPLE  
  59. GO  
  60. ALTER DATABASE[TrialsDB] SET READ_COMMITTED_SNAPSHOT OFF  
  61. GO  
  62. ALTER DATABASE[TrialsDB] SET HONOR_BROKER_PRIORITY OFF  
  63. GO  
  64. ALTER DATABASE[TrialsDB] SET RECOVERY FULL  
  65. GO  
  66. ALTER DATABASE[TrialsDB] SET MULTI_USER  
  67. GO  
  68. ALTER DATABASE[TrialsDB] SET PAGE_VERIFY CHECKSUM  
  69. GO  
  70. ALTER DATABASE[TrialsDB] SET DB_CHAINING OFF  
  71. GO  
  72. ALTER DATABASE[TrialsDB] SET FILESTREAM(NON_TRANSACTED_ACCESS = OFF)  
  73. GO  
  74. ALTER DATABASE[TrialsDB] SET TARGET_RECOVERY_TIME = 0 SECONDS  
  75. GO  
  76. ALTER DATABASE[TrialsDB] SET READ_WRITE  
  77. GO   

Create table with data

  1. USE[TrialsDB]  
  2. GO  
  3. /****** Object: Table [dbo].[Product] Script Date: 5/12/2016 10:54:48 AM ******/  
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8. CREATE TABLE[dbo].[Product](  
  9.     [ProductID][intNOT NULL, [Name][nvarchar](maxNOT NULL, [ProductNumber][nvarchar](25) NOT NULL, [MakeFlag][bitNOT NULL, [FinishedGoodsFlag][bitNOT NULL, [Color][nvarchar](15) NULL, [SafetyStockLevel][smallintNOT NULL, [ReorderPoint][smallintNOT NULL, [StandardCost][money] NOT NULL, [ListPrice][money] NOT NULL, [Size][nvarchar](5) NULL, [SizeUnitMeasureCode][nchar](3) NULL, [WeightUnitMeasureCode][nchar](3) NULL, [Weight][decimal](8, 2) NULL, [DaysToManufacture][intNOT NULL, [ProductLine][nchar](2) NULL, [Class][nchar](2) NULL, [Style][nchar](2) NULL, [ProductSubcategoryID][intNULL, [ProductModelID][intNULL, [SellStartDate][datetime] NOT NULL, [SellEndDate][datetime] NULL, [DiscontinuedDate][datetime] NULL, [rowguid][uniqueidentifier] ROWGUIDCOL NOT NULL, [ModifiedDate][datetime] NOT NULL  
  10. ON[PRIMARY] TEXTIMAGE_ON[PRIMARY]  
  11. GO  
  12. INSERT[dbo].[Product]([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES(1, N 'Adjustable Race', N 'AR-5381', 0, 0, NULL, 1000, 750, 0.0000, 0.0000, NULLNULLNULLNULL, 0, NULLNULLNULLNULLNULLCAST(0x0000921E00000000 AS DateTime), NULLNULL, N '694215b7-08f7-4c0d-acb1-d734ba44c0c8'CAST(0x00009A5C00A53CF8 AS DateTime))  
  13. INSERT[dbo].[Product]([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES(2, N 'Bearing Ball', N 'BA-8327', 0, 0, NULL, 1000, 750, 0.0000, 0.0000, NULLNULLNULLNULL, 0, NULLNULLNULLNULLNULLCAST(0x0000921E00000000 AS DateTime), NULLNULL, N '58ae3c20-4f3a-4749-a7d4-d568806cc537'CAST(0x00009A5C00A53CF8 AS DateTime))  
  14. INSERT[dbo].[Product]([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES(3, N 'BB Ball Bearing', N 'BE-2349', 1, 0, NULL, 800, 600, 0.0000, 0.0000, NULLNULLNULLNULL, 1, NULLNULLNULLNULLNULLCAST(0x0000921E00000000 AS DateTime), NULLNULL, N '9c21aed2-5bfa-4f18-bcb8-f11638dc2e4e'CAST(0x00009A5C00A53CF8 AS DateTime))  
  15. INSERT[dbo].[Product]([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES(4, N 'Headset Ball Bearings', N 'BE-2908', 0, 0, NULL, 800, 600, 0.0000, 0.0000, NULLNULLNULLNULL, 0, NULLNULLNULLNULLNULLCAST(0x0000921E00000000 AS DateTime), NULLNULL, N 'ecfed6cb-51ff-49b5-b06c-7d8ac834db8b'CAST(0x00009A5C00A53CF8 AS DateTime))  
  16. INSERT[dbo].[Product]([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES(316, N 'Blade', N 'BL-2036', 1, 0, NULL, 800, 600, 0.0000, 0.0000, NULLNULLNULLNULL, 1, NULLNULLNULLNULLNULLCAST(0x0000921E00000000 AS DateTime), NULLNULL, N 'e73e9750-603b-4131-89f5-3dd15ed5ff80'CAST(0x00009A5C00A53CF8 AS DateTime))  
  17. INSERT[dbo].[Product]([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES(317, N 'LL Crankarm', N 'CA-5965', 0, 0, N 'Black', 500, 375, 0.0000, 0.0000, NULLNULLNULLNULL, 0, NULL, N 'L 'NULLNULLNULLCAST(0x0000921E00000000 AS DateTime), NULLNULL, N '3c9d10b7-a6b2-4774-9963-c19dcee72fea'CAST(0x00009A5C00A53CF8 AS DateTime))  
  18. INSERT[dbo].[Product]([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES(318, N 'ML Crankarm', N 'CA-6738', 0, 0, N 'Black', 500, 375, 0.0000, 0.0000, NULLNULLNULLNULL, 0, NULL, N 'M 'NULLNULLNULLCAST(0x0000921E00000000 AS DateTime), NULLNULL, N 'eabb9a92-fa07-4eab-8955-f0517b4a4ca7'CAST(0x00009A5C00A53CF8 AS DateTime))   

Our database is ready, now create a Web API application in visual studio and then entity with the above mentioned database.

Creating Entity

Creating Entity

If you don’t know how to create an entity in your solution, please read that here. I have mentioned the steps to be followed in that article. Once you have created the entity, you are good to go and create a API controller with the entity created. If you do so, The CRUD actions will be created automatically for you. You may need to edit those actions according to your needs.

Web API 2 Controller with actions, using Entity Framework

Web API 2 Controller with actions, using Entity Framework

Select the Model Class, DBContext then name your controller and click OK. I hope a controller with the CRUD actions. Now we can modify that as follows.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.Entity;  
  5. using System.Data.Entity.Infrastructure;  
  6. using System.Linq;  
  7. using System.Net;  
  8. using System.Net.Http;  
  9. using System.Web.Http;  
  10. using System.Web.Http.Description;  
  11. using ControllerActionDescriptions.Models;  
  12. namespace ControllerActionDescriptions.Controllers  
  13. {  
  14.     public class ProductsController: ApiController   
  15.     {  
  16.         private TrialsDBEntities db = new TrialsDBEntities();#  
  17.         region GetProducts  
  18.         /// <summary>  
  19.         /// Get all the products available  
  20.         /// GET: api/Products  
  21.         /// </summary>  
  22.         public IQueryable < Product > GetProducts()   
  23.         {  
  24.             return db.Products;  
  25.         }#endregion# region GetProductWithParameter  
  26.         /// <summary>  
  27.         /// Get a single product by id  
  28.         /// GET: api/Products/5  
  29.         /// <param name="id"></param>  
  30.         /// </summary>  
  31.             [ResponseType(typeof(Product))]  
  32.         public IHttpActionResult GetProduct(int id)  
  33.         {  
  34.             Product product = db.Products.Find(id);  
  35.             if (product == null)  
  36.             {  
  37.                 return NotFound();  
  38.             }  
  39.             return Ok(product);  
  40.         }#endregion  
  41.         // PUT: api/Products/5  
  42.             [ResponseType(typeof(void))]  
  43.         public IHttpActionResult PutProduct(int id, Product product) {  
  44.                 if (!ModelState.IsValid)  
  45.                 {  
  46.                     return BadRequest(ModelState);  
  47.                 }  
  48.                 if (id != product.ProductID)  
  49.                 {  
  50.                     return BadRequest();  
  51.                 }  
  52.                 db.Entry(product).State = EntityState.Modified;  
  53.                 try {  
  54.                     db.SaveChanges();  
  55.                 } catch (DbUpdateConcurrencyException)  
  56.                 {  
  57.                     if (!ProductExists(id))  
  58.                     {  
  59.                         return NotFound();  
  60.                     } else  
  61.                     {  
  62.                         throw;  
  63.                     }  
  64.                 }  
  65.                 return StatusCode(HttpStatusCode.NoContent);  
  66.             }  
  67.             // POST: api/Products  
  68.             [ResponseType(typeof(Product))]  
  69.         public IHttpActionResult PostProduct(Product product)   
  70.         {  
  71.                 if (!ModelState.IsValid)  
  72.                 {  
  73.                     return BadRequest(ModelState);  
  74.                 }  
  75.                 db.Products.Add(product);  
  76.                 try {  
  77.                     db.SaveChanges();  
  78.                 } catch (DbUpdateException)   
  79.                 {  
  80.                     if (ProductExists(product.ProductID))  
  81.                     {  
  82.                         return Conflict();  
  83.                     } else  
  84.                     {  
  85.                         throw;  
  86.                     }  
  87.                 }  
  88.                 return CreatedAtRoute("DefaultApi"new   
  89.                                       {  
  90.                     id = product.ProductID  
  91.                 }, product);  
  92.             }  
  93.             // DELETE: api/Products/5  
  94.             [ResponseType(typeof(Product))]  
  95.         public IHttpActionResult DeleteProduct(int id)  
  96.         {  
  97.             Product product = db.Products.Find(id);  
  98.             if (product == null)  
  99.             {  
  100.                 return NotFound();  
  101.             }  
  102.             db.Products.Remove(product);  
  103.             db.SaveChanges();  
  104.             return Ok(product);  
  105.         }  
  106.         protected override void Dispose(bool disposing)  
  107.         {  
  108.             if (disposing)   
  109.             {  
  110.                 db.Dispose();  
  111.             }  
  112.             base.Dispose(disposing);  
  113.         }  
  114.         private bool ProductExists(int id)   
  115.         {  
  116.             return db.Products.Count(e => e.ProductID == id) > 0;  
  117.         }  
  118.     }  
  119. }  
Installing WebApiTestClient 

To install the package, please go to your Package Manage Console from NuGet Package Manager and run the following command.

  1. Install-Package WebApiTestClient   

You can always get the details about the package here.

Once you install the package, you can see some files are added to your Script and Area folder as preceding.

Script and Area Folder

Script and Area Folder

Configuring WebApiTestClient

To configure the WebApiTestClient, please go to the folder Areas->Views->Help and then click on Api.cshtml

Api Cshtml

Api Cshtml

This is the view shown when you click on each API in your help page. Now add the preceding code block to that view.

  1. @Html.DisplayForModel("TestClientDialogs")  
  2. @section Scripts  
  3. {  
  4. <link href="~/Areas/HelpPage/HelpPage.css" rel="stylesheet" type="text/css" />  
  5. @Html.DisplayForModel("TestClientReferences")  
  6. }  
Code Block

Code Block

Testing WebApiTestClient

Now run your API application and go to the help page for any controller action, you can see a button called Test API on the bottom. If you click on that you will get a pop where you can test your API action.

Test API Client Output

Test API Client Output

Now if you send your request by clicking the send button, you will get an output as follows.

Test API Client Output With Response

Test API Client Output With Response

You can always give id parameter as follows.

Test Client With Parameters

Test Client With Parameters

You can also give content-length and content-type in your post request as follows.

Test Client With Post

Test Client With Post

Test Client With PUT Request

Test Client With PUT Request

References

Author has already posted the source code in GitHub, please check here.

Happy coding!.

Conclusion

Did I miss anything that you may think is needed? Did you find this post useful? I hope you liked this article. Please share with me your valuable suggestions and feedback.

Your turn. What do you think?

A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.

Up Next
    Ebook Download
    View all
    Learn
    View all