Most Web API 2.0 methods I've seen return IHttpActionResult
, which is defined as an interface that "defines a command that asynchronously creates a System.Net.Http.HttpResponseMessage".
I'm a little confused about what's going on when a method is returning async Task<IHttpActionResult>
.
Why would you use one over the other? Or are these functionally identical - isn't IHttpActionResult
already asynchronous?
Your action may return an IHttpActionResult which performs the action asynchronously when the framework calls its ExecuteAsync . But if you must first make some other async calls before creating and returning the result, then you're forced to change the signature to async Task<IHttpActionResult> . That's all it is.
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.
The IHttpActionResult interface is contained in the System. Web. Http namespace and creates an instance of HttpResponseMessage asynchronously. The IHttpActionResult comprises a collection of custom in-built responses that include: Ok, BadRequest, Exception, Conflict, Redirect, NotFound, and Unauthorized.
Your action may return an IHttpActionResult
which performs the action asynchronously when the framework calls its ExecuteAsync
.
But if you must first make some other async calls before creating and returning the result, then you're forced to change the signature to async Task<IHttpActionResult>
. That's all it is.
If your controller action code doesn't use await
then you can switch back to the simpler signature. However, the result you return will still be asynchronous.
To be clear, in both cases, you are using asynchronous code.
The performance benefit is that - provided all calls to the deepest level are async - a web server thread is not blocked during disk or network I/O, your server can handle more requests with fewer resources.
Think carefully before calling Wait
or Result
on a Task, or creating a Task yourself within ASP.NET code.
Two legitimate reasons to hand-code, intentional multi-threading or parallelism for web server code are:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With