Treatment of generic responses in the Web API using .Net

Alegria Kilanda
4 min readNov 2, 2020

In software development when we talk about productivity, there’s no way we can’t talk about generics. In this article I present one of the ways to handle responses of a web api in a generic way using .Net.

1 — Creating the generic structure

First starts by creating a enum called EResponse, within it we define all kinds of responses that our web api will have.

Next we create a class called ResponseData, within it we have.

Code: it’s kind of response;

Status: it represents the state of the request, success or UnSuccess;

Message: it’s a simple informative text;

Data: it’s return data.

Exceptoins

Now we are going to create the Exceptoins, for each type of response we have an exception except OK.

As an example we have the exception NoDataException

Controller

After we define the struct we’re going to create the first controller called ResponseController, this controller is responsible for handling the responses.

Now we’re going to create another controller called BaseController, it’s the heart of our solution.

In it we have two delegates

These delegates are invoked when making a request, below we will present them with greater clarity.

Still within the BaseController, we have a method called Execute, it’s responsible to execute all resquests. Here we’re using the exceptions defined above, whenever the web API has an exception, it analyzes the type of exception and handles the response according to the type of exception. Here we can also write logs…

In the BaseController we have other auxiliary methods

2 — Using the generic structure

Now that we have finished defining our generic structure, now we are going to use.

We’re going to create a model class called car, within this class we are using DataAnnotations to validate some properties.

We’re going to create a controller called CarController, it extends the BaseController. Within each action of controller we call the execute method, in the first parameter we inform the type of return, in the second is all the business logic.

3 — Result

To test our API we used the swager.

Now, we are going to test the route create:

Case 1

The case 1, it presents a validation error scenario from DataAnnotations, it does the validation on line 10.

Parameters

Parameters

Response Body

Response Body

Case 2

The case 2, it presents a validation error scenario , it does the validation on line 12.

Parameters

Parameters

Response Body

Response Body

Case 3

The case 3, it presents a success scenario.

Parameters

Parameters

Response Body

Response Body

Case 1

The case 1, it returns NoData, it does validation on line 31.

Case 2

The case 2, it presents a success scenario.

The project is available on github for contributions and improvements.

Another version of this article has been created for .net core

--

--