Problem

How to implement asynchronous messaging using ASP.NET Core Web API.

Solution

Create an empty project and update the Startup class to add services and middleware for MVC.

Add a Controller.

Add models to send/receive via API.

Discussion

Communication with Web API can be synchronous (RPC) or asynchronous (messaging). For asynchronous communication, the client will -

  1. Send request
  2. Check its status
  3. Get result.
Send Request

The API will have a POST endpoint to accept the requests. It will usually store the request message in a queue for subsequent processing. This endpoint returns 202 (Accepted) status code along with the Location header for the endpoint to check the status of this request.


Check Status

API will have a GET endpoint that will either send 200 (OK) with status details for incomplete requests or 303 (See Other) with Location header for completed requests.


Note that 303 (See Other) doesn’t have a built-in method on base controller but it is easy enough to create your own.

Get Result

API will have a GET endpoint that will either send 200 (OK) for completed requests or 404 (Not Found) for incomplete requests.


Usage Scenarios

Asynchronous message based communication is good for long running processes and distributed systems (e.g. Microservices). The client and server usually have the following responsibilities in asynchronous communication.

Server

Client

Azure

Azure provides a lot of pieces involved in the section above, e.g. Azure ServiceBus for queues, Azure NoSQL for recording log, Azure Web Apps to host API and Azure WebJobs for background processing.

Source Code

GitHub