
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Test Chash in ASP.NET Web API
Testing WebApi involves sending a request and receiving the response. There are several ways to test the WebApi. Here we will test the WebApi using postman and swagger. Let us create a StudentController like below.
Student Model
namespace DemoWebApplication.Models{ public class Student{ public int Id { get; set; } public string Name { get; set; } } }
Student Controller
Example
using DemoWebApplication.Models; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace DemoWebApplication.Controllers{ public class StudentController : ApiController{ List<Student> students = new List<Student>{ new Student{ Id = 1, Name = "Mark" }, new Student{ Id = 2, Name = "John" } }; public IEnumerable<Student> Get(){ return students; } public Student Get(int id){ var studentForId = students.FirstOrDefault(x => x.Id == id); return studentForId; } } }
Test Using Swagger
Swagger is a specification for documenting REST API. It specifies the format (URL, method, and representation) to describe REST web services. The methods, parameters, and models description are tightly integrated into the server code, thereby maintaining the synchronization in APIs and its documentation.
In our application, using Manage Nuget packages install swagger.
Run our WebApi project and enter swagger/ui/index in the url.
The swagger will automatically list out the controller and its action method like below. We can expand the respective controller and test the endpoint using our request.
Get All Students Request
Get All Students Response
Get Students for Id Request
Get Students for Id Response
Test Using Postman
Postman is a popular API client that makes it easy for developers to create, share, test and document APIs. This is done by allowing users to create and save simple and complex HTTP/s requests, as well as read their responses. The result - more efficient and less tedious work. Postman can be installed as an application or can be send through browser like below.