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 14 great preprocessors for developers who love to code Sometimes it seems like the rules of programming are designed to make coding a chore. Here are 14 ways preprocessors can help make software development fun again. By Peter Wayner Nov 18, 2024 10 mins Development Tools Software Development feature Designing the APIs that accidentally power businesses Well-designed APIs, even those often-neglected internal APIs, make developers more productive and businesses more agile. By Jean Yang Nov 18, 2024 6 mins APIs Software Development news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks news Go language evolving for future hardware, AI workloads The Go team is working to adapt Go to large multicore systems, the latest hardware instructions, and the needs of developers of large-scale AI systems. By Paul Krill Nov 15, 2024 3 mins Google Go Generative AI Programming Languages Resources Videos