IC Improve Code Recipes

Recipe 16.2 · C#

From Global.asax and HttpModules to Middleware

Problem

Request-wide behavior lives in Global.asax and a few IHttpModule classes: a maintenance-mode switch, security headers, URL rewrites, error mail. The order they run in depends on web.config and the IIS pipeline, and turning maintenance mode on means editing a file on every server.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not to copy: Global.asax with config read on every request.
protected void Application_BeginRequest(object sender, EventArgs e)
{
    if (ConfigurationManager.AppSettings["Maintenance"] == "true"
        && !Request.Path.EndsWith("Maintenance.aspx"))
    {
        Response.Redirect("~/Maintenance.aspx");
    }
    Response.AddHeader("X-Frame-Options", "DENY");
}

protected void Application_Error(object sender, EventArgs e)
{
    EmailHelper.SendError(Server.GetLastError());
}

The redirect returns a 302 and then a 200, so monitoring tools and search engines think the site is fine. Editing web.config to flip the switch recycles the application pool and drops every session.

The improved recipe

C#
using System.Collections.Generic;
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace ImproveCode.Web.Middleware;

public sealed class MaintenanceOptions
{
    public bool Enabled { get; set; }
    public string Message { get; set; } =
        "The site is down for scheduled maintenance.";
    public int RetryAfterSeconds { get; set; } = 900;
    public List<string> BypassPaths { get; set; } = ["/health"];
}

public sealed class MaintenanceModeMiddleware(
    RequestDelegate next,
    IOptionsMonitor<MaintenanceOptions> options)
{
    public async Task InvokeAsync(HttpContext context)
    {
        MaintenanceOptions current = options.CurrentValue;
        if (!current.Enabled ||
            current.BypassPaths.Exists(
                p => context.Request.Path.StartsWithSegments(p)))
        {
            await next(context);
            return;
        }

        HttpResponse response = context.Response;
        response.StatusCode = StatusCodes.Status503ServiceUnavailable;
        response.Headers.RetryAfter = current.RetryAfterSeconds
            .ToString(CultureInfo.InvariantCulture);
        response.ContentType = "text/plain; charset=utf-8";
        await response.WriteAsync(current.Message);
    }
}

public sealed class SecurityHeadersMiddleware(RequestDelegate next)
{
    public Task InvokeAsync(HttpContext context)
    {
        context.Response.OnStarting(() =>
        {
            IHeaderDictionary headers = context.Response.Headers;
            headers.XContentTypeOptions = "nosniff";
            headers.XFrameOptions = "DENY";
            headers["Referrer-Policy"] =
                "strict-origin-when-cross-origin";
            return Task.CompletedTask;
        });

        return next(context);
    }
}

public static class MiddlewareSetup
{
    public static IServiceCollection AddMaintenanceMode(
        this IServiceCollection services, IConfiguration config)
    {
        services.Configure<MaintenanceOptions>(
            config.GetSection("Maintenance"));
        return services;
    }

    public static IApplicationBuilder UseMaintenanceMode(
        this IApplicationBuilder app) =>
        app.UseMiddleware<MaintenanceModeMiddleware>();

    public static IApplicationBuilder UseSecurityHeaders(
        this IApplicationBuilder app) =>
        app.UseMiddleware<SecurityHeadersMiddleware>();
}

How it works

Middleware is a chain of components, each receiving the HttpContext and a delegate for the next one. The order is the order of the Use... calls in Program.cs, visible in one place, which replaces the guesswork of Global.asax events plus modules registered in web.config.

MaintenanceModeMiddleware returns 503 Service Unavailable with a Retry-After header. That's the status load balancers, uptime monitors and crawlers understand as "temporarily down". The health endpoint stays reachable through BypassPaths. Because the middleware reads IOptionsMonitor<T>.CurrentValue, changing Maintenance:Enabled in appsettings.json (or an environment-specific file, or Azure App Configuration) takes effect without a restart.

SecurityHeadersMiddleware adds its headers in OnStarting, just before the response is sent, so they apply to every response, including those produced by later middleware. The typed header properties on IHeaderDictionary catch misspelled header names at compile time.

Here is how the old events map:

Web Forms ASP.NET Core
Application_Start Program.cs
Application_BeginRequest Middleware
IHttpModule Middleware
IHttpHandler (.ashx) Endpoint or controller
Application_Error UseExceptionHandler
Session_Start No direct equivalent

Variations and pitfalls

  • Middleware runs for every request, including static files if it's registered before UseStaticFiles. Put cheap checks early and expensive ones late, after routing, where you can also read endpoint metadata.
  • For a maintenance page with styling, return a static HTML file instead of plain text, but keep the 503 status.
  • Session_Start was often used to initialize session values. In ASP.NET Core, initialize lazily: read the value and create it if missing, as the typed session wrapper in the next recipe does.
  • For headers like Content-Security-Policy, start in report-only mode. A strict policy added in one step will break a legacy app's inline scripts.