Introduction

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

Requirements:

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:

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.