Custom Action Results in ASP.NET Web API

Introduction

In this article we will discuss how to create custom action results in ASP.NET Web API.

Requirements:

  • Visual Studio 2012
  • ASP.NET WEB API 2 Project Template Installed.

Creating Custom Action Result

The first version of ASP.NET Web API supports 3 types of action results. They are HttpResponseMessage, Void and Type of Entity or Model(Some other type as per ASP.NET/WEB-API of Microsoft). But in WEB API 2, Microsoft had introduced another powerful Action result called IhttpActionResult. This interface acts as a factory for HttpResponseMessage. If we use IhttpActionResult as the return type of web api's method internally convert the value into Http Response Message.

The best use of IhttpActionResult is that it provides some built in Http Response Messages such as Ok, NotFound, BadRequest, Found, UnAuthorized, etc.

As IhttpActionResult provides built in Http Response Messages, we can create our own Action Result by implementing IhttpActionResult's ExecuteAsync method.

Step 1: Create a folder called CustomActionResult.

Step 2: Create a class called MyCustomResultForOk and derive or inherit it from IhttpActionResult.

CustomResult

Step: 3
action method 
 
Points:
  • We have Created the custom action result called MyCustomActionResultOk.
  • Created Parameterized constructor in order to send Student Object from the WEB API's action method.
  • Implemented ExcecuteAsync method.

Step 4: Created the action method called GetStudent (Student Student) to return the Student Object as HTTP Response Message with Custom Action Result.

Controller

Step 5: If we run the application and see it in Rest client, the response body will be having Student Object.

Student Object

Summary

We saw how to create Custom Action Result in ASP.Net Web API.

Up Next
    Ebook Download
    View all
    Learn
    View all