Can we build fully Asynchronous ASP.NET Core 2 Web API? Yes, of course, this article lets us build one such Web API using ASP.NET Core 2.
In .NET or .NET Core world, applications can work asynchronously using async await keyword. It has simplified async way of working. We will use async await for building fully asynchronous Web API.
Whats the agenda?
- Understanding async await
- Demo ASP.NET Core 2 Web API
- Asynchronous Web API methods
- Using Entity Framework 2.0
- Web API testing
Understanding async await
The async await feature itself needs a big blog post, recommend to read through if you’re new to using async await
One of prominent best practices in async programming is Async all the way i.e. you shouldn’t mix synchronous and asynchronous code without carefully considering the consequences. In particular, it’s usually a bad idea to block on async code by calling Task.Wait or Task.Result.
It’s essential to understand best practices of async await.
Demo ASP.NET Core 2 Web API
We will be continuing with the ContactsAPI build with Entity Framework 2.0.
Why are we using EF 2.0? EF 2.0 provides all the asynchronous methods to perform the CRUD related operation.
Methods like FindAsync(), SaveAsync(), ToListAsync() etc. provides an asynchronous way of working with EF Data Context.
Asynchronous ASP.NET Core 2 Web API methods
ASP.NET Core 2 allows making asynchronous Web API by using async await keyword. The Action methods in Controller should use the async keyword in the method signature, the method should return Taskcontaining IActionResult.
The Web API method should call further methods using await keyword. Those methods should also have implemented async await pattern in them. Remember Async All the way 
The ContactsController would look like as below
Using Entity Framework 2.0 async methods
As we have used EF 2.0, it provides most of the methods asynchronously, we will modify the ContactsRepositoryinterface & class work in an async way. The refactored code will look like this
Testing the Web API
Download the source from Github repo, run the project, test web api’s using Postman or Fiddler.
Remember Async All the way !!
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.