How to return custom result type from an action method in C# ASP.NET WebAPI?

We can create our own custom class as a result type by implementing IHttpActionResult interface. IHttpActionResult contains a single method, ExecuteAsync, which asynchronously creates an HttpResponseMessage instance.

public interface IHttpActionResult
{
   Task ExecuteAsync(CancellationToken
   cancellationToken);
}

If a controller action returns an IHttpActionResult, Web API calls the ExecuteAsync method to create an HttpResponseMessage. Then it converts the HttpResponseMessage into an HTTP response message.

Example

To have our own custom result we must create a class that implements IHttpActionResult interface.

using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class CustomResult : IHttpActionResult{
      string _value;
      HttpRequestMessage _request;
      public CustomResult(string value, HttpRequestMessage request){
         _value = value;
         _request = request;
      }
      public Task ExecuteAsync(CancellationToken
      cancellationToken){
         var response = new HttpResponseMessage(){
            Content = new StringContent($"Customized Result: {_value}"),
            RequestMessage = _request
         };
         return Task.FromResult(response);
      }
   }
}

Contoller Action

Example

using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class DemoController : ApiController{
      public IHttpActionResult Get(int id){
         List students = new List{
            new Student{
               Id = 1,
               Name = "Mark"
            },
            new Student{
               Id = 2,
               Name = "John"
            }
         };
         var studentForId = students.FirstOrDefault(x => x.Id == id);
         return new CustomResult(studentForId.Name, Request);
      }
   }
}

Here is the postman output of the endpoint which returns custom result.

Updated on: 2020-08-19T11:54:42+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements