IC Improve Code Recipes

Recipe 16.2 · Python

From Global.asax and HttpModules to Middleware

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

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.

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.

Requirements: Python 3.12+. Install: pip install flask werkzeug

Python Global request hooks that re-read config per request and e-mail every error (p355_r16_2_global_asax_request_hooks_before.py)
"""Global request hooks that re-read config per request and e-mail every error

Source: ImproveCode, Chapter 16, Recipe 16.2 "From Global.asax and HttpModules to Middleware"
Section: The way it's often written
Book page: 355  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
Global.asax events become Flask before_request/after_request/errorhandler hooks;
ConfigurationManager.AppSettings becomes a configparser file read on every request.
"""

import configparser

from flask import Flask, redirect, request
from flask.typing import ResponseReturnValue
from werkzeug.wrappers import Response

app = Flask(__name__)


class EmailHelper:  # placeholder, as in the original
    @staticmethod
    def send_error(ex: BaseException) -> None: ...


# Not to copy: global hooks with config read on every request.
@app.before_request
def application_begin_request() -> ResponseReturnValue | None:
    settings = configparser.ConfigParser()
    settings.read("app.ini")
    if (
        settings.get("appSettings", "Maintenance", fallback=None) == "true"
        and not request.path.endswith("Maintenance.aspx")
    ):
        return redirect("/Maintenance.aspx")
    return None


@app.after_request
def add_frame_header(response: Response) -> Response:
    response.headers.add("X-Frame-Options", "DENY")
    return response


@app.errorhandler(Exception)
def application_error(ex: Exception) -> ResponseReturnValue:
    EmailHelper.send_error(ex)
    return "", 500

The improved recipe

Requirements: Python 3.12+. Install: pip install fastapi pydantic starlette

Python Maintenance-mode (503 + Retry-After) and security-headers middleware (p355_r16_2_maintenance_and_security_headers_middleware.py)
"""Maintenance-mode (503 + Retry-After) and security-headers middleware

Source: ImproveCode, Chapter 16, Recipe 16.2 "From Global.asax and HttpModules to Middleware"
Section: The improved recipe
Book page: 355-357  -- original C# listing
Converted from C# to Python.
ASP.NET Core middleware becomes Starlette middleware on FastAPI; MaintenanceOptions is a
pydantic model and IOptionsMonitor becomes a callable that returns the current options
(e.g. one backed by pydantic-settings that reloads), read on each request.
"""

from collections.abc import Awaitable, Callable

from fastapi import FastAPI
from pydantic import BaseModel, Field
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import PlainTextResponse, Response
from starlette.types import ASGIApp

CallNext = Callable[[Request], Awaitable[Response]]


class MaintenanceOptions(BaseModel):
    enabled: bool = False
    message: str = "The site is down for scheduled maintenance."
    retry_after_seconds: int = 900
    bypass_paths: list[str] = Field(default_factory=lambda: ["/health"])


def _starts_with_segments(path: str, prefix: str) -> bool:
    path, prefix = path.casefold(), prefix.rstrip("/").casefold()
    return path == prefix or path.startswith(prefix + "/")


class MaintenanceModeMiddleware(BaseHTTPMiddleware):
    def __init__(self, app: ASGIApp, options: Callable[[], MaintenanceOptions]) -> None:
        super().__init__(app)
        self._options = options

    async def dispatch(self, request: Request, call_next: CallNext) -> Response:
        current = self._options()
        if not current.enabled or any(
            _starts_with_segments(request.url.path, p) for p in current.bypass_paths
        ):
            return await call_next(request)

        return PlainTextResponse(
            current.message,
            status_code=503,
            headers={"Retry-After": str(current.retry_after_seconds)},
            media_type="text/plain; charset=utf-8",
        )


class SecurityHeadersMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next: CallNext) -> Response:
        response = await call_next(request)
        headers = response.headers
        headers["X-Content-Type-Options"] = "nosniff"
        headers["X-Frame-Options"] = "DENY"
        headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
        return response


def use_maintenance_mode(app: FastAPI, options: Callable[[], MaintenanceOptions]) -> FastAPI:
    app.add_middleware(MaintenanceModeMiddleware, options=options)
    return app


def use_security_headers(app: FastAPI) -> FastAPI:
    app.add_middleware(SecurityHeadersMiddleware)
    return app

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.