ASP.NET – How to use a BackgroundService for long-running and periodic tasks

In ASP.NET, when you need a long-running background task, or need to run a task periodically, you can implement IHostedService or BackgroundService and register your class as a hosted service in Startup. As you may have already encountered, if you try to run a long-running background task, the web server will randomly kill your task … Read more ASP.NET – How to use a BackgroundService for long-running and periodic tasks

ASP.NET – InvalidOperationException: Synchronous operations are disallowed

Problem You’re trying to do synchronous IO operations in ASP.NET and you get the following exception: System.InvalidOperationException: ‘Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true The reason you’re getting this is because server option AllowSynchronousIO is false. Starting in ASP.NET Core 3.0, this is false by default. Solution Microsoft turned this setting … Read more ASP.NET – InvalidOperationException: Synchronous operations are disallowed

ASP.NET – How to enable CORS for all endpoints

The simplest way to enable CORS for all endpoints is by adding a default CORS policy in the Startup class. The following code shows the two lines of code to add: Note: Put whatever CORS policy makes sense for you. In the code above, I am simply allowing everything. Test CORS locally To test this … Read more ASP.NET – How to enable CORS for all endpoints

ASP.NET – Use Swagger to generate API documentation

The simplest way to add API documentation is to use Swagger. You can configure it to generate an API documentation page and even send requests to your endpoints. Here’s what it looks like: In this article I’ll show how to install and configure Swagger with the following features (shown in the image above): Generates an … Read more ASP.NET – Use Swagger to generate API documentation

ASP.NET – Async SSE endpoint

Server-Sent Events (SSE) allow a client to subscribe to messages on a server. The server pushes new messages to the client as they happen. This is an alternative to the client polling the server for new messages. In this article I’ll show how to implement the messaging system shown in the diagram below. This uses … Read more ASP.NET – Async SSE endpoint