Action Results in Web API 2
by Mike Wasson
This topic describes how ASP.NET Web API converts the return value from a controller action into an HTTP response message.
A Web API controller action can return any of the following:
- void
- HttpResponseMessage
- IHttpActionResult
- Some other type
Depending on which of these is returned, Web API uses a different mechanism to create the HTTP response.
Return type | How Web API creates the response |
---|---|
void | Return empty 204 (No Content) |
HttpResponseMessage | Convert directly to an HTTP response message. |
IHttpActionResult | Call ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message. |
Other type | Write the serialized return value into the response body; return 200 (OK). |
The rest of this topic describes each option in more detail.
void
If the return type is void
, Web API simply returns an empty HTTP response with status code 204 (No Content).
Example controller:
[!code-csharpMain]
1: public class ValuesController : ApiController
2: {
3: public void Post()
4: {
5: }
6: }
HTTP response:
[!code-consoleMain]
1: HTTP/1.1 204 No Content
2: Server: Microsoft-IIS/8.0
3: Date: Mon, 27 Jan 2014 02:13:26 GMT
HttpResponseMessage
If the action returns an HttpResponseMessage, Web API converts the return value directly into an HTTP response message, using the properties of the HttpResponseMessage object to populate the response.
This option gives you a lot of control over the response message. For example, the following controller action sets the Cache-Control header.
[!code-csharpMain]
1: public class ValuesController : ApiController
2: {
3: public HttpResponseMessage Get()
4: {
5: HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
6: response.Content = new StringContent("hello", Encoding.Unicode);
7: response.Headers.CacheControl = new CacheControlHeaderValue()
8: {
9: MaxAge = TimeSpan.FromMinutes(20)
10: };
11: return response;
12: }
13: }
Response:
[!code-consoleMain]
1: HTTP/1.1 200 OK
2: Cache-Control: max-age=1200
3: Content-Length: 10
4: Content-Type: text/plain; charset=utf-16
5: Server: Microsoft-IIS/8.0
6: Date: Mon, 27 Jan 2014 08:53:35 GMT
7:
8: hello
If you pass a domain model to the CreateResponse method, Web API uses a media formatter to write the serialized model into the response body.
[!code-csharpMain]
1: public HttpResponseMessage Get()
2: {
3: // Get a list of products from a database.
4: IEnumerable<Product> products = GetProductsFromDB();
5:
6: // Write the list to the response body.
7: HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, products);
8: return response;
9: }
Web API uses the Accept header in the request to choose the formatter. For more information, see Content Negotiation.
IHttpActionResult
The IHttpActionResult interface was introduced in Web API 2. Essentially, it defines an HttpResponseMessage factory. Here are some advantages of using the IHttpActionResult interface:
- Simplifies unit testing your controllers.
- Moves common logic for creating HTTP responses into separate classes.
- Makes the intent of the controller action clearer, by hiding the low-level details of constructing the response.
IHttpActionResult contains a single method, ExecuteAsync, which asynchronously creates an HttpResponseMessage instance.
[!code-csharpMain]
1: public interface IHttpActionResult
2: {
3: Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);
4: }
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.
Here is a simple implementaton of IHttpActionResult that creates a plain text response:
[!code-csharpMain]
1: public class TextResult : IHttpActionResult
2: {
3: string _value;
4: HttpRequestMessage _request;
5:
6: public TextResult(string value, HttpRequestMessage request)
7: {
8: _value = value;
9: _request = request;
10: }
11: public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
12: {
13: var response = new HttpResponseMessage()
14: {
15: Content = new StringContent(_value),
16: RequestMessage = _request
17: };
18: return Task.FromResult(response);
19: }
20: }
Example controller action:
[!code-csharpMain]
1: public class ValuesController : ApiController
2: {
3: public IHttpActionResult Get()
4: {
5: return new TextResult("hello", Request);
6: }
7: }
Response:
[!code-consoleMain]
1: HTTP/1.1 200 OK
2: Content-Length: 5
3: Content-Type: text/plain; charset=utf-8
4: Server: Microsoft-IIS/8.0
5: Date: Mon, 27 Jan 2014 08:53:35 GMT
6:
7: hello
More often, you will use the IHttpActionResult implementations defined in the System.Web.Http.Results namespace. The ApiController class defines helper methods that return these built-in action results.
In the following example, if the request does not match an existing product ID, the controller calls ApiController.NotFound to create a 404 (Not Found) response. Otherwise, the controller calls ApiController.OK, which creates a 200 (OK) response that contains the product.
[!code-csharpMain]
1: public IHttpActionResult Get (int id)
2: {
3: Product product = _repository.Get (id);
4: if (product == null)
5: {
6: return NotFound(); // Returns a NotFoundResult
7: }
8: return Ok(product); // Returns an OkNegotiatedContentResult
9: }
Other Return Types
For all other return types, Web API uses a media formatter to serialize the return value. Web API writes the serialized value into the response body. The response status code is 200 (OK).
[!code-csharpMain]
1: public class ProductsController : ApiController
2: {
3: public IEnumerable<Product> Get()
4: {
5: return GetAllProductsFromDB();
6: }
7: }
A disadvantage of this approach is that you cannot directly return an error code, such as 404. However, you can throw an HttpResponseException for error codes. For more information, see Exception Handling in ASP.NET Web API.
Web API uses the Accept header in the request to choose the formatter. For more information, see Content Negotiation.
Example request
[!code-consoleMain]
1: GET http://localhost/api/products HTTP/1.1
2: User-Agent: Fiddler
3: Host: localhost:24127
4: Accept: application/json
Example response:
[!code-consoleMain]
1: HTTP/1.1 200 OK
2: Content-Type: application/json; charset=utf-8
3: Server: Microsoft-IIS/8.0
4: Date: Mon, 27 Jan 2014 08:53:35 GMT
5: Content-Length: 56
6:
7: [{"Id":1,"Name":"Yo-yo","Category":"Toys","Price":6.95}]
|