Asynchronous Messaging Using ASP.NET Core 2.0 Web API

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

  • On receiving the request message, store the message in a queue or database for later processing.
  • There will be a component (e.g. windows service) running in the background to process messages off the queue.
  • Once the processing is complete, a record in a database (SQL or NoSQL) will be updated to reflect the status of request.
  • API endpoints for Check Status and Get Result will use this database to respond to client requests accordingly.

Client

  • After sending the request to server API, keep a record (in-memory or database) of the Location header, which contains the endpoint to ping for checking request status.
  • There will be a component (e.g. windows service) running in the background to periodically call the status endpoint.
  • Once the status endpoint returns 303 (See Other), use the Location header to access the result of processing.
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