- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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<HttpResponseMessage> 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<HttpResponseMessage> 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<Student> students = new List<Student>{ 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.
Advertisements