Leverage action results to return data as an HttpResponseMessage object from your Web API controller method ASP.Net Web API is a lightweight framework used for building stateless and RESTful HTTP services. You can take advantage of Action Results in Web API to return data from the Web API controller methods. Getting started Let’s create a Web API project first. To do this, create a blank ASP.Net project in Visual Studio 2015 and check the Web API checkbox when selecting the project template. Next, save the project with a name. You would notice that a blank ASP.Net project is created. Right-click on the Controllers solution folder and click Add –> Controller to create a new Web API controller. Select the “Web API 2 Controller – Empty” when prompted for in the window that pops up next. Save the controller with a name. Let’s assume the name of the controller for this example is “DefaultController”. Let’s create an entity class named Contact. public class Contact { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } Next, add the following method to the DefaultController. public CustomActionResult<Contact> Get() { Contact contact = new Contact(); contact.Id = 1; contact.FirstName = "Joydip"; contact.LastName = "Kanjilal"; return new CustomActionResult<Contact>(HttpStatusCode.OK, contact); } Note the usage of the CustomActionResult class while returning data from the controller method. Now let’s create a CustomActionResult class just to ensure that your code compiles — we’ll implement this class later. public class CustomActionResult<T> : IHttpActionResult { public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { throw new NotImplementedException(); } } Working with ActionResults Your Web API controller can return any one of the following value types: HttpResponseMessage: in this case your Web API would convert the return value into an Http response message object and return it. IHttpActionResult: in this case the Web API runtime converts the return value to an Http response message object (an HttpResponseMessage instance is created asynchronously) internally and returns it. Usage of the IHttpActionResult interface (introduced in Web API 2) simplifies unit testing your Web API controllers and also wraps the creation of an HttpResponseMessage object. void: in this case, your Web API would return an empty Http response with a status code of 204. Other types: in this case, your Web API would take advantage of the appropriate media formatter to serialize and return data from the Web API controller method with a response status code of 200. The following code snippet shows how you can use return HttpResponseMessage from your Web API controller method. [Route("contact")] public HttpResponseMessage Get() { HttpResponseMessage message = Request.CreateResponse<Contact>(HttpStatusCode.OK, contact); return message; } Let’s now implement a custom action result which we’ll use to return data from the Web API we created. Creating a custom ActionResult To create a custom action result class, all you need to do is, create a class that implements the IActionResult interface and overrides the ExecuteAsync method. The following code snippet shows how you can use Generics to create a custom action result class. public class CustomActionResult<T> : IHttpActionResult { private System.Net.HttpStatusCode statusCode; T data; public CustomActionResult(System.Net.HttpStatusCode statusCode, T data) { this.statusCode = statusCode; this.data = data; } } The following code snippet shows how you can create the response object, populate it with the necessary data and return it. public HttpResponseMessage CreateResponse(System.Net.HttpStatusCode statusCode, T data) { HttpRequestMessage request = new HttpRequestMessage(); request.Properties.Add(System.Web.Http.Hosting.HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration()); HttpResponseMessage response = request.CreateResponse(statusCode, data); return response; } The ExecuteAsync method calls the CreateResponse method and passes the status code and data to it as parameter. public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { return Task.FromResult(CreateResponse(this.statusCode, this.data)); } Consuming the Web API To consume the Web API you have just created, you can create a console application and then import the “WebApiContrib.Formatting.ProtoBuf” package to your project via NuGet. Assuming that you have created the client to consume the Web API we implemented earlier, here’s the code listing that shows how you can consume the Web Api. static void Main(string[] args) { var client = new HttpClient { BaseAddress = new Uri("http://localhost:37019/") }; HttpResponseMessage response = client.GetAsync("api/Default").Result; if (response.IsSuccessStatusCode) { Contact contact = response.Content.ReadAsAsync<Contact>().Result; Console.WriteLine("Id = "+ contact.Id + " First Name: " + contact.FirstName + " Last Name: " + contact.LastName); } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } Console.ReadKey(); } Related content feature What is Rust? Safe, fast, and easy software development Unlike most programming languages, Rust doesn't make you choose between speed, safety, and ease of use. Find out how Rust delivers better code with fewer compromises, and a few downsides to consider before learning Rust. By Serdar Yegulalp Nov 20, 2024 11 mins Rust Programming Languages Software Development how-to Kotlin for Java developers: Classes and coroutines Kotlin was designed to bring more flexibility and flow to programming in the JVM. Here's an in-depth look at how Kotlin makes working with classes and objects easier and introduces coroutines to modernize concurrency. By Matthew Tyson Nov 20, 2024 9 mins Java Kotlin Programming Languages analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks Resources Videos