Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to return custom result type from an action method in C# ASP.NET WebAPI?
In ASP.NET Web API, you can create custom result types by implementing the IHttpActionResult interface. This interface provides a flexible way to customize HTTP responses beyond the standard return types like Ok(), BadRequest(), or NotFound().
The IHttpActionResult interface contains a single method that asynchronously creates an HttpResponseMessage instance, giving you full control over the HTTP response.
Syntax
The IHttpActionResult interface has the following structure −
public interface IHttpActionResult
{
Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);
}
How It Works
When 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 that gets sent to the client.
Creating a Custom Result Type
To create a custom result type, you must implement the IHttpActionResult interface in a class −
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
namespace CustomResultExample
{
public class CustomResult : IHttpActionResult
{
private string _value;
private HttpRequestMessage _request;
public CustomResult(string value, HttpRequestMessage request)
{
_value = value;
_request = request;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage()
{
Content = new StringContent($"Customized Result: {_value}"),
RequestMessage = _request
};
return Task.FromResult(response);
}
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
public class DemoController : ApiController
{
public IHttpActionResult Get(int id)
{
var students = new[]
{
new Student { Id = 1, Name = "Mark" },
new Student { Id = 2, Name = "John" }
};
var student = Array.Find(students, x => x.Id == id);
if (student == null)
return new CustomResult("Student not found", Request);
return new CustomResult(student.Name, Request);
}
public static void Main(string[] args)
{
Console.WriteLine("Custom Result Example - Web API Controller");
Console.WriteLine("This demonstrates IHttpActionResult implementation");
}
}
}
The output when calling the API endpoint would be −
Customized Result: Mark
Advanced Custom Result with JSON Response
You can create more sophisticated custom results that return JSON responses with custom headers and status codes −
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
namespace AdvancedCustomResult
{
public class JsonCustomResult : IHttpActionResult
{
private readonly object _data;
private readonly HttpStatusCode _statusCode;
private readonly HttpRequestMessage _request;
public JsonCustomResult(object data, HttpStatusCode statusCode, HttpRequestMessage request)
{
_data = data;
_statusCode = statusCode;
_request = request;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var json = Newtonsoft.Json.JsonConvert.SerializeObject(_data);
var response = new HttpResponseMessage(_statusCode)
{
Content = new StringContent(json, Encoding.UTF8, "application/json"),
RequestMessage = _request
};
response.Headers.Add("X-Custom-Header", "CustomResultType");
return Task.FromResult(response);
}
}
public class ApiController
{
protected HttpRequestMessage Request { get; set; } = new HttpRequestMessage();
}
public class ProductController : ApiController
{
public IHttpActionResult GetProduct(int id)
{
var product = new { Id = id, Name = "Sample Product", Price = 29.99 };
return new JsonCustomResult(product, HttpStatusCode.OK, Request);
}
public static void Main(string[] args)
{
var controller = new ProductController();
var result = controller.GetProduct(1);
Console.WriteLine("Advanced Custom Result created with JSON response");
Console.WriteLine("Status: 200 OK with custom headers");
}
}
}
The output of the above code is −
Advanced Custom Result created with JSON response Status: 200 OK with custom headers
Common Use Cases
Custom Error Responses: Creating standardized error formats across your API.
Response Formatting: Applying consistent formatting or wrapping to all responses.
Custom Headers: Adding specific headers like authentication tokens or tracking information.
Conditional Logic: Implementing complex logic to determine response format based on request context.
Conclusion
Custom result types in ASP.NET Web API provide powerful flexibility for customizing HTTP responses. By implementing IHttpActionResult, you can create reusable, testable components that encapsulate response logic and maintain consistency across your API endpoints.
