Thursday 12 July 2018

Building fully Asynchronous ASP.NET Core 2 Web API

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.

1 comment:

  1. Very nice blog, thank you for the details on the shots, it will make me progress.

    Voyance en ligne

    ReplyDelete

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...