Prerequisite

  • Basic C# coding knowledge
  • Minimum knowledge of Web API
  • Understanding the REST service
  • Basic understanding of Fiddler

What are Web API Action Results?

Before we get into our topic, types of Web API Action results, let’s discuss Web API service methods and REST service response.(If you are aware of action method concept in Web API, you can directly start from Types of Web API Action results section). Let’s assume, we are writing a Web API service method to return the user details based on the User ID parameter. As a beginner, we create a method with UserID as the parameter and the return type would be UserProfile entity type as shown in the following code (I have added the User profile model and UserProfileDB classes on the same location, but as per the standards, we have to create them in a separate folder structure).

The Code

  1. public class UserProfileController : ApiController  
  2.     {  
  3.         [HttpGet]  
  4.         [Route("UserProfile/GetUserProfile/{UserId}")]  
  5.         public UserProfile GetUserProfile(int UserId)  
  6.         {  
  7.             return new UserProfileDB().GetUserProfile(UserId);  
  8.         }  
  9.     }  
  10.   
  11.     public class UserProfile  
  12.     {  
  13.         public int UserId { get; set; }  
  14.         public string UserName { get; set; }  
  15.         public string Location { get; set; }  
  16.         public int PIN { get; set; }  
  17.         public int Age { get; set; }  
  18.         public string Sex { get; set; }  
  19.         public string Occupation { get; set; }  
  20.         public float AnnualIncome { get; set; }  
  21.         public string MaritalStatus { get; set; }  
  22.         public string Nationality { get; set; }  
  23.     }  
  24.     public class UserProfileDB  
  25.     {  
  26.         public UserProfile GetUserProfile(int UserId)  
  27.         {  
  28.      //write the code logic to retrieve user data from database  
  29.             return new UserProfile();  
  30.         }  
  31.     }  

In the above code, the return type is UserProfile where we call here Web API Action Result. When the client calls this service by passing the UserID, the client will get the user details in JSON/XML format depending on the configuration.

Minimum things to know about the response

When we are working with Web API, we should be aware of the returned result. As Web API service is a REST enabled service, we should beware of / take care of the following things at least.

Highlight the above 3 by taking Fiddler Raw response as an example for the UserProfile in the following figure. (I have called the GetUserProfile  service from Fiddler and the response is as follows).


C#

Types of Web API Action Results

Let’s see how we are going to handle returned types in Web API. Web API provides a facility to return any of the following kinds of Action Results.

  1. Void
  2. Any Entity/Datatype
  3. HttpResponseMessage
  4. IHttpActionResult

Void 

Void means it doesn’t return anything. So, let’s see how it works on Web API action method.

Following action method returns void.

  1.         [HttpGet]  
  2.         public void LogMessageinDB(string Message)  
  3.         {  
  4.             new UserProfileDB().LogMessageinDB(Message);  
  5.         }  

I am calling this service method using Fiddler's composer option.

C#

And, see the response of the service.

C#

We won’t get the data from the service and the status will always be 204 - no content.

When we have to use Void action results

When there is a requirement where the next process is not dependent on the action result, like any kind of loggings.

Any Entity/Datatype

Web API action method can contain any entity type as return type. As mentioned in the first example of What is Web API Action Results, we can use any entity type as the return type. But the problem here is that we get 200 (OK) status code every time on a successful response.

  1.      [HttpGet]  
  2.      [Route("UserProfile/GetUserProfile/{UserId}")]  
  3.      public UserProfile GetUserProfile(int UserId)  
  4.      {  
  5.          return new UserProfileDB().GetUserProfile(UserId);  
  6.      }  

Following is the result of the above service call in Fiddler.

Result in the Fiddler

C#

When you observe the above picture, the status code is 200 and the result is in JSON format at the bottom.

When we have to use this kind of action result

It is not recommended to use because of two reasons -

  1. We cannot explain/convey the client with the various status codes as we get 200 (OK) status code every time.
  2. There is no guarantee that the above service will return the required result at every time. There could be an issue with the data or the DB Server or anything can happen. In these situations, the consumer won’t get the data and will get an error in response, i.e., the status code 500 always. Moreover, the client receives complete stack trace error message.

    C#

To overcome these problems, Web API provided Action results, like HttpResponseMessage and IHttpActionResult.

HttpResponseMessage

To customize the action result, we can use HttpResponseMessage as return type (action result) of an action method.

We can customize the response by providing status code, content type, and data to be returned to HttpResponseMessage.

Go through the following example.

  1.        [HttpGet]  
  2.        [Route("UserProfile/GetUserLoginID/{UserId}")]  
  3.        public HttpResponseMessage GetUserLoginId(int UserId)  
  4.        {  
  5.            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Accepted,"Ravikiran");  
  6.            response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain");  
  7.            return response;  
  8.        }  

When we call the above action method, we get the result as following (shown in the Fiddler).

C#

Result of the above call will be as follows -

C#

We can observe that the default return type is modified to text/plain and the status code is 202 (Accepted).

We can return the complex type data using HttpResponseMessage.

IHttpActionResult

IHttpActionResult has been introduced in Web API 2. This is a little-advanced concept of HttpResponseMessage. IHttpActionResult ultimately returns HttpResponseMessage by providing the customization and reusability features to the developer.

IHttpActionResult contains ExecuteAsync method to create an instance of HttpResponseMessage asynchronously. We have to add some code logic in the implemented class as per our requirement. When user/client calls the action method of IHttpActionResult type, Web API automatically hits the ExecuteAsync method.

Steps to implement IHttpActionResult

Initially, we have to create the return type by inheriting IHttpActionResult. Please see the following code snippet.

  1. public class UserProfileReturnType : IHttpActionResult  
  2.     {  
  3.         UserProfile userProfile;  
  4.         HttpRequestMessage httpRequestMessage;  
  5.   
  6.         HttpResponseMessage httpResponseMessage;  
  7.         public UserProfileReturnType(UserProfile data, HttpRequestMessage request)  
  8.         {  
  9.             userProfile = data;  
  10.             httpRequestMessage = request;  
  11.         }  
  12.   
  13.         public System.Threading.Tasks.Task<HttpResponseMessage> ExecuteAsync(System.Threading.CancellationToken cancellationToken)  
  14.         {  
  15.             httpResponseMessage =httpRequestMessage.CreateResponse(HttpStatusCode.Found, userProfile);  
  16.             return System.Threading.Tasks.Task.FromResult(httpResponseMessage);  
  17.         }  
  18.     }  

In the above code, we have created UserProfileReturnType and given the definition for ExecuteAsync Method by adding some custom logic.

Now, we can use UserProfileReturnType as return type whenever we want to return the UserProfile.

  1.        [HttpGet]  
  2.        [Route("UserProfile/GetUserProfileIHAR/{UserId}")]  
  3.        public IHttpActionResult GetUserProfileIHAR(int UserId)  
  4.        {  
  5.            //get the user profileof UserID   
  6.            UserProfile userProfile = new UserProfileDB().GetUserProfile(UserId);  
  7.   
  8.            //return UserProfileReturnType HttpResponseMessage  
  9.            return new UserProfileReturnType(userProfile, Request);  
  10.        }  

I am going to call GetUserProfileIHAR service method by passing UserId using Fiddler.

C#

The result will be as follows.

C#

Next Recommended Readings