Use Of HttpResponseMessage In WebAPI

Introduction

Here, you will learn the uses of HttpResponseMessage WebAPI. For better understanding. we will go step by step with simple examples.
 
Prerequisites
  • Visual Studio
  • SQL Management Studio 
  • Basic knowledge of Entity Framework
  • Basic knowledge of WebAPI
Article Flow 
  • Create a table in database and insert values
  • Create ASP.NET WebAPI Empty Project
  • Integrate Entity Framework
  • Create Controller with Logics
  • Processing HttpResponseMessage
Create a table in database and insert values
 
Here, we are going to play with some collection records with HttpResponseMessage so that I am going to create a table with some dummy records. Here is the query to create a table.
  1. CREATE TABLE [dbo].[Employee](  
  2. [ID] [bigint] IDENTITY(1,1) NOT NULL,  
  3. [Name] [nvarchar](maxNULL,  
  4. [Designation] [nvarchar](200) NULL,  
  5. [Location] [nvarchar](200) NULL,  
  6. CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED  
  7. (  
  8.    [ID] ASC  
  9. ))  
After execution of this query, the table design will be as below.
 
 
 
Insert the dummy record as below and execute the below query to get these same values.
  1. USE [CSharpCorner]  
  2. GO  
  3. SET IDENTITY_INSERT [dbo].[Employee] ON  
  4. GO  
  5. INSERT [dbo].[Employee] ([ID], [Name], [Designation], [Location]) VALUES (1, N'Gnanavel Sekar', N'Software Engineer', N'Chennai')  
  6. GO  
  7. INSERT [dbo].[Employee] ([ID], [Name], [Designation], [Location]) VALUES (3, N'Robert', N'Application Developer', N'Chennai')  
  8. GO  
  9. INSERT [dbo].[Employee] ([ID], [Name], [Designation], [Location]) VALUES (4, N'Ramar', N'TechLead', N'Chennai')  
  10. GO  
  11. SET IDENTITY_INSERT [dbo].[Employee] OFF  
  12. GO  
 

Now, we have completed the database design with a table. Let's create an empty ASP.NET WebAPI project.
 
Create ASP.NET WebAPI Empty Project
 
To create a new ASP.NET WebAPI project, follow the below steps one by one.
 
Step 1
 
Select New Project -> Web -> ASP.NET Web Application. Name your project (Here, I mentioned it as "HttpResponse") and click OK. This step is common for MVC, WebAPI, and WebForms.
 
 
 
Step 2
 
Now, select Empty WebAPI Project and click OK. 

 
 
Step 3

In the below image, you can see that the project has been created with basic architecture of WebAPI.

 
Integrate Entity Framework
 
To integrate Entity Connection with our project, select ADO.NET EntityDataModel.
 
 
 
I have already discussed about database first approach here. Once you integrate the Entity Framework, you will get the below screen.
 
 
 
Create Controller with Logics
 
Now, create a Controller to write a logic. For that, right click on your Controller folder under the solution and select "Web API 2 Controller-Empty" and click  "Add".
 
 
 
Now, name your Controller.
 
 
 
Now, the Controller has been created as below.
  
 
First, we retrieve the employee data from database by employee id. Now, we can do our logics by using this entity "CSharpConrnerEntities".
 
 
 
Process of HttpResponseMessage
 
Before moving to the example, we should know about WebAPI. ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. 
 
Here, I am getting the employee record who matches with that respective id.
  1. public Employee GetEmployeeById(long id)  
  2. {  
  3.    return csharp.Employees.Where(a => a.ID == id).FirstOrDefault();  
  4. }  
In case there is no record with respective id, it will return the null value with success status to the client.
Here, what we have to do is that we need to return as "employee is not found" with respective id and should throw the status of not found.
We can achieve this by using the  HttpResponseMessage. 
 
HttpResponseMessage and its uses
 
HttpResponseMessage works with HTTP protocol to return the data with status/error. When we talk about response messages in Web API, we simply represent the receiving of some information from the method(s) that we created in Web API so that we can know what kind of response we will get, such as - success or failure. We can use HTTPResponseMessage to return the data as well as some user friendly messages.
 
Syntax or Structure of  HttpResponseMessage
  1. public HttpResponseMessage ActionName(parameter(s))  
  2. {  
  3.    return //status with data (or) status (or) data  
  4. }  
Implement HttpResponseMessage
  1. /// <summary>  
  2. /// Working with HttpResponseMessage  
  3. /// </summary>  
  4. /// <remarks>  
  5. /// If employee found for respective id means it will return the employee data with httpstatus of OK else it will return the httpstatus as notfound and message of Employee not found  
  6. /// </remarks>  
  7. /// <param name="id"></param>  
  8. /// <returns></returns>  
  9. public HttpResponseMessage GetEmployeeById(long id) {  
  10.         Employee emp = csharp.Employees.Where(a => a.ID == id).FirstOrDefault();  
  11.         if (emp != null) {  
  12.             return Request.CreateErrorResponse < Employee > (HttpStatusCode.OK, emp);  
  13.         } else {  
  14.             return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Emplyee not found");  
  15.         }  
Now, as you can see above, we have used a HttpResponseMessage as the return type for our get method "GetEmployeeById" that will “CreateResponse” and return's the employee data with “HttpStatusCode.OK” if the employee exists for the Id provided incase no such employee exists then it will create a “CreateErrorResponse” and that will be returning the message “Employee Not Found” and “HttpStatusCode.NotFound”, here the CreateErrorResponse used to return the status of http like ok,NotFound,InternalServerError and etc with data/message.
 
for better exception handling here we will use the Try and catch
  1. public HttpResponseMessage GetEmployeeById(long id) {  
  2.     try {  
  3.         Employee emp = csharp.Employees.Where(a => a.ID == id).FirstOrDefault();  
  4.         if (emp != null) {  
  5.             return Request.CreateErrorResponse < Employee > (HttpStatusCode.OK, emp);  
  6.         } else {  
  7.             return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Emplyee not found");  
  8.         }  
  9.     } catch (Exception ex) {  
  10.         return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);  
  11.     }  
  12. }  
Summary
 
In this article, we learned to create an empty ASP.NET WebAPI project as well as how to return the message/data with “HttpStatusCode” from our WebAPI Action using the HttpResponseMessage.
 
I hope it was helpful. Your feedback and comments are always welcome.


Similar Articles