IC Improve Code Recipes

Recipe 16.6 · C#

Migrating Incrementally with YARP and System.Web Adapters

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.

C#
using System;
using ImproveCode.Web;
using ImproveCode.Web.Middleware;
using ImproveCode.Web.Navigation;
using ImproveCode.Web.Session;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = WebApplication.CreateBuilder(args);
string legacyUrl = builder.Configuration["LegacyApp:Url"]
    ?? throw new InvalidOperationException("LegacyApp:Url missing.");

builder.Services.AddAppMvc();                               // 16.1
builder.Services.AddMaintenanceMode(builder.Configuration); // 16.2
builder.Services.AddUserSession();                          // 16.3
builder.Services.AddNavigation(builder.Configuration);      // 16.5

builder.Services.AddHttpForwarder();
builder.Services.AddSystemWebAdapters()
    .AddJsonSessionSerializer(options =>
    {
        options.RegisterKey<int>("CustomerId");
    })
    .AddRemoteAppClient(options =>
    {
        options.RemoteAppUrl = new Uri(legacyUrl);
        options.ApiKey = builder.Configuration["LegacyApp:ApiKey"]
            ?? throw new InvalidOperationException(
                "LegacyApp:ApiKey missing.");
    })
    .AddSessionClient()
    .AddAuthenticationClient(true);

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseSecurityHeaders();
app.UseMaintenanceMode();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseUserSession();
app.UseSystemWebAdapters();

app.MapDefaultControllerRoute()
    .RequireSystemWebAdapterSession();

// Everything not handled above goes to the Web Forms app.
app.MapForwarder("/{**catch-all}", legacyUrl)
    .AllowAnonymous()
    .Add(static b => ((RouteEndpointBuilder)b).Order = int.MaxValue);

app.Run();

Configuration (keep the API key in user secrets or a vault, Chapter 6):

JSON
{
  "LegacyApp": {
    "Url": "https://localhost:44300"
  },
  "Maintenance": {
    "Enabled": false
  }
}

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.SystemWebAdapters package contains System.Web.HttpContext, HttpRequest, HttpResponse, HttpSessionState and related types. A class library that uses HttpContext.Current can 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). AddSessionClient makes the new app fetch session state from the Framework app over HTTP for endpoints marked with RequireSystemWebAdapterSession, 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 HttpApplication events and IHttpModule code, and map IHttpHandler classes, which helps with shared infrastructure. Check the documentation for your version.
  • They don't run Web Forms. No .aspx pages, 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.

C#
using System;
using System.Configuration;
using System.Web;
using Microsoft.AspNetCore.SystemWebAdapters.Hosting;

public class Global : HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        HttpApplicationHost.RegisterHost(builder =>
        {
            builder.Services.AddSystemWebAdapters()
                .AddJsonSessionSerializer(options =>
                    options.RegisterKey<int>("CustomerId"))
                .AddRemoteAppServer(options =>
                    options.ApiKey = ConfigurationManager
                        .AppSettings["RemoteAppApiKey"])
                .AddSessionServer()
                .AddAuthenticationServer();
        });
    }
}

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.