Computer >> Computer tutorials >  >> Programming >> C#

How can we test C# Asp.Net WebAPI?


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.

How can we test C# Asp.Net WebAPI?

Run our WebApi project and enter swagger/ui/index in the url.

How can we test C# Asp.Net WebAPI?

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

How can we test C# Asp.Net WebAPI?

Get All Students Response

How can we test C# Asp.Net WebAPI?

Get Students for Id Request

How can we test C# Asp.Net WebAPI?

Get Students for Id Response

How can we test C# Asp.Net WebAPI?

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.

How can we test C# Asp.Net WebAPI?

Get All Students Request and Response

How can we test C# Asp.Net WebAPI?

Get Students For Id Request and Response

How can we test C# Asp.Net WebAPI?