joydip_kanjilal
Contributor

How to work with ActionResults in Web API

opinion
Nov 11, 20154 mins
Software Development

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();

        }

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author