How To Implement A "Maintenance Mode" in ASP.NET Core
Tags: tutorial, dotnet, aspdotnet, csharp
Published: 2023-04-07 13:15:00


In this article, you will both learn how to put your asp.Net Core app into maintenance mode using the framework’s “App offline file” feature, and how to implement your own maintenance mode logic when you need more control.

Let’s start with the fast solution when you just need to put it in maintenance quickly. 

## Using the framework’s maintenance feature

For a fast implementation, you can use [asp .Net Core’s maintenance feature](https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/app-offline) by adding a file called “app_offline.htm” in the **root of your solution**. This is a very nice, quick and easy solution that lets you create a HTM(L) file with the layout and message that you want to show to your users you are performing maintenance on the app.

This feature is called the “App offline file”, and has some things to consider, like:

* the file can be maximally 4Gb in size (should be more than enough)

* it needs your app to receive another request to become online after removing the file

* in specific situations, the app might not shut down immediately

You can read Microsoft’s documentation on the App Offline file feature, here: [App Offline file - learn.microsoft.com](https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/app-offline)

The App Offline file feature is very nice for small projects, MVP’s or demo setups, and side projects. 

If you want more control of how to implement maintenance mode, and want to add logic- or signalling features for a more controlled process, you will need to code your own solution. I will explain this in the following part.

## Rolling out your own maintenance mode feature

Creating your own feature has the advantage that you don’t rely on a file being put into place on the server, and you can implement all kinds of extra things, i.e.:

* use application logic, a database value or a configuration file value to enable/disable maintenance mode (read on to see the configuration file implementation example)

* you can log the timestamps to register when and how long maintenance mode was applied for reference

* you could implement signalling logic like sending an email, SMS, etc. to service desk employees and/or other key users or people that need to know.

To implement your own maintenance mode in ASP .NET Core, you can follow these steps:

**Step 1. **Create a new middleware component that will intercept all requests to the application and return a “maintenance mode” page instead of processing the request. This middleware component should be registered in the request pipeline before any other middleware component.

Here’s an example implementation of a maintenance mode middleware component:
```csharp
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

public class MaintenanceMiddleware
{
    private readonly RequestDelegate _next;

    public MaintenanceMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        // Check if maintenance mode is enabled
        if (IsMaintenanceModeEnabled())
        {
            await context.Response.WriteAsync("Maintenance mode is enabled. Please try again later.");
            return;
        }

        await _next(context);
    }

    private bool IsMaintenanceModeEnabled()
    {
        // Implement your own logic here to determine if maintenance mode is enabled
        return true; // Return true for demo purposes
    }
}
```

**Step 2.** In the Startup.cs file, add the maintenance mode middleware component to the request pipeline:

```csharp
public void Configure(IApplicationBuilder app, IHostingEnvironment env) 
{ 
    // Other middleware components here... 
 
    app.UseMiddleware<MaintenanceMiddleware>(); 
 
    // Other middleware components here... 
}
```
**Step 3.** Implement the logic to enable and disable maintenance mode. 

This could be done using a configuration file, a database, or any other means that suits your application.

Here’s an example implementation of a configuration-based maintenance mode toggle:
```csharp
public static class MaintenanceMode 
{ 
    public static bool IsEnabled { get; set; } 
} 
 
public class Startup 
{ 
    public IConfiguration Configuration { get; } 
 
    public Startup(IConfiguration configuration) 
    { 
        Configuration = configuration; 
    } 
 
    public void ConfigureServices(IServiceCollection services) 
    { 
        // Other service configurations here... 
 
        // Add configuration-based maintenance mode toggle 
        services.Configure<MaintenanceModeOptions>(Configuration.GetSection("MaintenanceMode")); 
    } 
 
    public void Configure(IApplicationBuilder app, IHostingEnvironment env) 
    { 
        // Other middleware components here... 
 
        app.UseMiddleware<MaintenanceMiddleware>(); 
 
        // Other middleware components here... 
    } 
} 
 
public class MaintenanceModeOptions 
{ 
    public bool IsEnabled { get; set; } 
}
```
With these changes, you can now enable or disable maintenance mode by updating the configuration value for MaintenanceModeOptions.IsEnabled.

### Configuration file example

Here’s an example of the appsettings.json configuration file that could be used to configure the maintenance mode toggle:

```json
{ 
  "MaintenanceMode": { 
    "IsEnabled": false 
  } 
}
```
## Concluding

Besides the technical implementation aspect — which I’ve shown you in this article — make sure to think about what option suits your development and deployment processes most.

Nowadays, techniques and tools are often used to minimize the pain of maintaining your application in production. 
Things like DevOps, Continues Integration and Continues Deployment (CI/CD), deployment slots, and hot swappable environments have made a “maintenance mode” unnecessary in many scenarios, but not all.

And that, dear reader, is all I’ve got for you on maintenance mode for Asp .Net Core.

![In this article, you've learned how to add a maintenance mode to your ASP.Net Core solution](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fbzqtuiyf8oww83tjg2p.gif)

Hopefully this article gave you some food for thought, and a good starting point if you decide to apply a maintenance mode feature for your solution. 

Code hard, Ship harder 🔥

~

*Do you work on .Net solutions with lots of SQL / LINQ and do want to save time by converting SQL into LINQ code or the other way around? ***Check out [LINQ Me Up — Convert SQL queries into LINQ code and vice versa using AI](http://www.linqmeup.com/)**