Recipe 16.6 · Python
Migrating Incrementally with YARP and System.Web Adapters
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
- The way it's often written
- The improved recipe
- How it works
- Variations and pitfalls
- On .NET Framework
Problem
The Web Forms application has hundreds of pages and a decade of business rules. A full rewrite would take a year or more, with nothing delivered until the end, and history says it will be late. You need to move to ASP.NET Core page by page while users keep working in one application, with one login and one URL.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
The traditional plan is a freeze on the old system, a separate team rebuilding everything, and a weekend cutover. The freeze never holds: the business keeps changing the old system, the new one chases a moving target, and the project stalls somewhere short of the finish with two systems to maintain.
The improved recipe
Use the strangler-fig pattern. Put a new ASP.NET Core application in front of the old one. It serves the routes that have been migrated and forwards every other request to the Web Forms application through YARP, Microsoft's reverse proxy library. The System.Web adapters let the two applications share session and authentication while both are running.
Packages: Yarp.ReverseProxy and Microsoft.AspNetCore.SystemWebAdapters.CoreServices in the new app; Microsoft.AspNetCore.SystemWebAdapters.FrameworkServices in the Web Forms app; Microsoft.AspNetCore.SystemWebAdapters in shared class libraries.
Configuration (keep the API key in user secrets or a vault, Chapter 6):
{
"LegacyApp": {
"Url": "https://localhost:44300"
},
"Maintenance": {
"Enabled": false
}
}
Requirements: Python 3.12+. Install: pip install fastapi httpx starlette uvicorn
"""Compose the new app and forward everything else to the legacy app (strangler fig)
Source: ImproveCode, Chapter 16, Recipe 16.6 "Migrating Incrementally with YARP and System.Web Adapters"
Section: The improved recipe
Book page: 373-374 -- original C# listing
Converted from C# to Python.
WebApplication becomes FastAPI configured from appsettings.json; YARP's MapForwarder
becomes a catch-all route appended last that relays requests with httpx. System.Web
adapters have no Python equivalent: the remote session/auth client is noted in place.
"""
import json
import os
from pathlib import Path
from typing import Any
import httpx
from fastapi import FastAPI, Request
from fastapi.responses import Response
from fastapi.routing import APIRoute
from fastapi.staticfiles import StaticFiles
from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware
from p353_r16_1_app_controller_and_auth_setup import add_app_mvc
from p355_r16_2_maintenance_and_security_headers_middleware import (
MaintenanceOptions,
use_maintenance_mode,
use_security_headers,
)
from p360_r16_3_session_middleware_setup import add_user_session
from p369_r16_5_config_driven_navigation_menu import add_navigation
_HOP_BY_HOP = {
"connection", "keep-alive", "transfer-encoding", "upgrade",
"host", "content-length", "content-encoding",
}
def _required(config: dict[str, Any], section: str, key: str) -> str:
value = config.get(section, {}).get(key)
if value is None:
raise RuntimeError(f"{section}:{key} missing.")
return value
def create_app(config_path: str = "appsettings.json") -> FastAPI:
config: dict[str, Any] = json.loads(Path(config_path).read_text(encoding="utf-8"))
legacy_url = _required(config, "LegacyApp", "Url")
development = os.environ.get("APP_ENVIRONMENT") == "Development"
app = FastAPI(debug=development)
add_app_mvc(app) # 16.1
use_maintenance_mode( # 16.2
app, lambda: MaintenanceOptions.model_validate(config.get("Maintenance", {}))
)
app.state.navigation = add_navigation(config) # 16.5
# System.Web adapters remote-app client (shared session key CustomerId:int,
# remote authentication) has no Python counterpart; the key is still required.
_required(config, "LegacyApp", "ApiKey")
# Starlette runs the middleware added last first, so these are added in
# reverse of the C# pipeline order (HTTPS redirect -> headers -> ... -> session).
add_user_session(app, _required(config, "Session", "SecretKey")) # 16.3
use_security_headers(app)
if not development:
@app.middleware("http")
async def hsts(request: Request, call_next): # type: ignore[no-untyped-def]
response = await call_next(request)
response.headers["Strict-Transport-Security"] = "max-age=2592000"
return response
app.add_middleware(HTTPSRedirectMiddleware)
app.mount("/static", StaticFiles(directory="static"), name="static")
client = httpx.AsyncClient(base_url=legacy_url, follow_redirects=False)
async def forward(request: Request, catch_all: str) -> Response:
headers = {k: v for k, v in request.headers.items() if k.lower() not in _HOP_BY_HOP}
upstream = await client.request(
request.method,
"/" + catch_all,
params=request.query_params.multi_items(),
headers=headers,
content=await request.body(),
)
out = {k: v for k, v in upstream.headers.items() if k.lower() not in _HOP_BY_HOP}
return Response(upstream.content, upstream.status_code, out)
# Everything not handled above goes to the Web Forms app. Appended directly so it
# is matched last and skips the router's fallback auth (AllowAnonymous).
app.router.routes.append(
APIRoute(
"/{catch_all:path}",
forward,
methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],
include_in_schema=False,
)
)
return app
if __name__ == "__main__":
import uvicorn
uvicorn.run(create_app())
How it works
Users only ever see the new application's URL. When a request arrives, routing tries the migrated controllers first. MapForwarder registers a catch-all route with the lowest possible priority (Order = int.MaxValue), so anything not yet migrated is proxied to the Web Forms application, with its own .aspx pages, postbacks and ViewState, unchanged. AllowAnonymous stops the new app's fallback policy from blocking those requests; the legacy app keeps enforcing its own security until each page moves.
Migrating a page means building its replacement as a controller and view in the new app and deploying. The route now matches in ASP.NET Core and the proxy stops seeing it. Start with read-only screens and high-traffic pages, and leave the oldest, most tangled ones for last, or retire them.
The System.Web adapters are often misunderstood, so here is what they do and don't do:
- They provide a System.Web API surface on ASP.NET Core. The
Microsoft.AspNetCore.SystemWebAdapterspackage containsSystem.Web.HttpContext,HttpRequest,HttpResponse,HttpSessionStateand related types. A class library that usesHttpContext.Currentcan target .NET Standard 2.0 and run in both applications; on .NET Framework the types forward to the real System.Web. - They share session through the legacy app (remote session).
AddSessionClientmakes the new app fetch session state from the Framework app over HTTP for endpoints marked withRequireSystemWebAdapterSession, and write it back afterwards. Every key must be registered with a type (RegisterKey<int>("CustomerId")) on both sides so it can be serialized as JSON. This costs a network call per request, so mark only the endpoints that need it. - They share authentication (remote authentication).
AddAuthenticationClient(true)makes the new app ask the Framework app who the current user is, based on the legacy authentication cookie. Users log in once, in the old app, until you move login itself. - Recent versions emulate parts of the old pipeline. They can run some
HttpApplicationevents andIHttpModulecode, and mapIHttpHandlerclasses, which helps with shared infrastructure. Check the documentation for your version. - They don't run Web Forms. No
.aspxpages, server controls,ViewState, master pages or page lifecycle on ASP.NET Core. Pages must be rebuilt as MVC views, Razor Pages or Blazor components.
Variations and pitfalls
- Remote session and remote authentication are migration bridges, not end states. Plan the step where login moves to the new app (ASP.NET Core Identity or an identity provider) and session moves to ASP.NET Core session. A typed
IUserSession(Recipe 16.3) keeps that switch out of your controllers. - With remote authentication as the default scheme, the authentication middleware asks the legacy app who the user is on every request, including requests that are then forwarded to it. Watch the extra load and latency, and if the legacy app is down, the new app can't authenticate anyone either.
- Static files, scripts and images referenced by legacy pages pass through the proxy too. Check absolute URLs and
~/paths in the old app, and turn off the old app's direct public binding once the proxy is in front. - Hosting both apps on one IIS server works: the Core app on the public site, the Framework app on an internal binding. On Azure, two App Services with the legacy one restricted to the proxy's outbound addresses works too.
- If you prefer configuration-driven routing over a single forwarder, YARP's
AddReverseProxy().LoadFromConfig(...)with a catch-all route does the same job and supports load balancing and health checks. - Microsoft's upgrade tooling for this pattern has changed names over the years. The building blocks underneath, YARP and the System.Web adapters, are what you need to understand.
On .NET Framework
The Web Forms app needs a matching registration. With version 2.x of Microsoft.AspNetCore.SystemWebAdapters.FrameworkServices, it goes in Global.asax.cs. This listing targets .NET Framework 4.7.2 or later and was not compiled with the rest of the chapter; check the package documentation for the version you install.
The ApiKey must match the new app's LegacyApp:ApiKey. It authenticates the session and authentication calls between the two apps, so treat it as a secret. The client validates its format at startup: it must be 32 hexadecimal characters, so a freshly generated GUID (Guid.NewGuid().ToString("N")) works.
Requirements: Python 3.12+. Install: pip install flask
"""Legacy-app side: expose its session and auth to the new app behind an API key
Source: ImproveCode, Chapter 16, Recipe 16.6 "Migrating Incrementally with YARP and System.Web Adapters"
Section: On .NET Framework
Book page: 376 -- original C# listing
Converted from C# to Python.
Global.asax Application_Start + AddRemoteAppServer become a Flask app factory registering
a small blueprint (no Python System.Web adapters exist). Only registered keys
(CustomerId:int) are shared, as JSON; the API key comes from configuration.
"""
import os
from typing import Any
from flask import Blueprint, Flask, abort, jsonify, request, session
REGISTERED_KEYS: dict[str, type] = {"CustomerId": int} # RegisterKey<int>("CustomerId")
def _remote_app_server(api_key: str) -> Blueprint:
bp = Blueprint("remote_app", __name__, url_prefix="/systemweb-adapters")
@bp.before_request
def check_api_key() -> None:
if not api_key or request.headers.get("X-Remote-App-Api-Key") != api_key:
abort(401)
@bp.get("/session") # AddSessionServer
def get_session() -> Any:
return jsonify({k: session.get(k) for k in REGISTERED_KEYS})
@bp.put("/session")
def put_session() -> Any:
data = request.get_json(force=True) or {}
for key, type_ in REGISTERED_KEYS.items():
if key in data:
session[key] = None if data[key] is None else type_(data[key])
return "", 204
@bp.get("/authenticate") # AddAuthenticationServer
def authenticate() -> Any:
user = session.get("User")
if user is None:
abort(401)
return jsonify(user)
return bp
def create_app() -> Flask: # Application_Start
app = Flask(__name__)
app.register_blueprint(_remote_app_server(os.environ.get("REMOTE_APP_API_KEY", "")))
return app