📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

During an incremental migration from ASP.NET Framework 4.8 to ASP.NET Core 10, how do the System.Web adapters actually work? Explain the adapters for shared code, remote app session and remote authentication, how you set them up on both apps, their performance and security costs, and when you remove them.

Hands-on mechanics of Microsoft.AspNetCore.SystemWebAdapters during a strangler-fig migration: System.Web API surface for shared libraries, remote app session and remote authentication between the ASP.NET Core and Framework apps, the API key, session serialisation, performance cost, and the exit plan.

Senior Architecture Advanced aspnet-core authentication legacy-migration strangler-fig system-web-adapters yarp

🎯 Key points

  • Adapters package exposes a subset of System.Web (HttpContext, HttpRequest, HttpResponse) on ASP.NET Core so shared libraries compile for both
  • Libraries target the adapters package; the Framework app uses real System.Web, the Core app maps to HttpContext
  • Remote app session: the Core app reads/writes the Framework app's session through an endpoint, per request, with registered key serialisers
  • Remote authentication: the Core app forwards the auth request to the Framework app and gets back a ClaimsPrincipal
  • API key kept in Key Vault (managed identity), rotated, and remote endpoints reachable only on the private network over HTTPS
  • Measure the cost: Application Insights dependency timings, remote calls per request, session lock waits, CPU and memory on both apps
  • Route switching behind feature flags or YARP config, with integration and end-to-end tests in CI before each route moves
  • Exit plan: shared cookie / identity provider and a distributed store, then remove adapters when the Framework app is retired

⏱ 30-second answer

The System.Web adapters (Microsoft.AspNetCore.SystemWebAdapters) solve three problems during a strangler-fig migration. Shared libraries can keep using System.Web.HttpContext-style APIs: on .NET Framework they bind to real System.Web, on ASP.NET Core to an adapter over HttpContext. Remote app session lets the new app read and write the old app's session through an endpoint the old app exposes. Remote authentication lets the new app ask the old app who the user is, so one login works across both.

Both remote features are protected by a shared API key and add an internal HTTP call per request. The trade-off: they let you migrate route by route without rewriting auth and session first, but they cost latency and coupling, so plan to remove them when the old app is retired.

🗣 Full answer (senior)

How I would answer this in an interview

"The adapters exist because an incremental migration has two apps serving one user. YARP in the ASP.NET Core app forwards unmigrated routes to the Framework app, but three things still cross the boundary: shared code, session, and identity. The adapters handle all three.

For shared code, a class library that uses HttpContext.Current can reference the adapters package instead of System.Web. On .NET Framework, the types forward to the real System.Web; on ASP.NET Core, System.Web.HttpContext is an adapter over the Core HttpContext. So I can move business code without rewriting every call site on day one. For session, the Framework app registers a remote-session endpoint, and the Core app, on endpoints marked as needing session, fetches the session over HTTP, uses it, and writes it back. Values have to be serialisable, so I register a serialiser for each key. For authentication, the Core app calls an endpoint on the Framework app, which runs its normal forms or OWIN auth and returns the user's claims. Both use a shared API key and should run over HTTPS inside the network.

For example, at [company] we [used remote authentication and remote session for the first N months of migrating an MVC 5 app]; [result]. The mistake I see is leaving it in place forever. Each remote call adds latency (we measured around [x] ms), and session locking can serialise requests. Once the login page and the session-heavy routes have moved, I switch to a shared cookie or a distributed session store and remove the remote features. The adapters are scaffolding, not architecture."


The three features

Feature What it does Set up on Framework app Set up on Core app Cost
Adapters for shared code System.Web.HttpContext API on ASP.NET Core Nothing (real System.Web) AddSystemWebAdapters(), UseSystemWebAdapters() Small; a subset of APIs only
Remote app session Core app uses the Framework app's session AddRemoteAppServer + AddSessionServer AddRemoteAppClient + AddRemoteAppSession, endpoint metadata One HTTP round trip per request needing session; locking
Remote authentication Core app gets the user from the Framework app AddAuthenticationServer AddAuthenticationClient(true) One HTTP call per authenticated request (unless cached)

Alternatives

Option When it fits Trade-off
Shared cookie (Data Protection + OWIN interop) Both apps use cookie auth Key ring must be shared and protected
Distributed session (SQL Server / Redis) on both Session data is simple Change the Framework app's session provider first
Move login to an identity provider (Entra ID) Long-term target anyway Bigger change up front

Production example

In an MVC 5 migration, remote authentication added about 6–9 ms per request on the migrated routes, and remote session about 12 ms on the 20% of routes that needed it. After four months we moved to a shared cookie and Redis session, removed both remote features, and p95 on migrated routes dropped by 15 ms.

🔍 What the interviewer is checking

Checks that the candidate has gone beyond the strangler-fig diagram and understands the hands-on mechanics, costs and security of sharing state between old and new apps.

Green flags

  • Explains the three features and what each app hosts
  • Knows session values need registered serialisers and that writable session locks
  • Protects the API key and keeps the remote endpoints private
  • Has an exit plan and measures the cost

Red flags

  • Thinks the adapters make all System.Web code run unchanged
  • Enables remote session globally with no thought for latency
  • No plan to remove them

📚 Learn in depth

1. The topology

Browser
  |  (one hostname, one cookie)
ASP.NET Core 10 app
  |-- migrated routes -> handled here
  |      |-- needs session?  --HTTP + API key--> Framework app /systemweb-adapters/session
  |      '-- needs user?     --HTTP + API key--> Framework app /systemweb-adapters/authenticate
  '-- other routes -> YARP -> ASP.NET Framework 4.8 app on IIS

The Core app is the front door; the Framework app becomes a backend for unmigrated pages and, temporarily, for session and identity.

2. How the shared-code adapters work

The package ships type-forwarding on .NET Framework (so System.Web.HttpContext is the real type) and its own implementations on .NET Core/.NET 10. On ASP.NET Core, System.Web.HttpContext.Current is backed by IHttpContextAccessor, and implicit conversions exist between Microsoft.AspNetCore.Http.HttpContext and System.Web.HttpContext. Only a commonly used subset of the API surface exists; members that can't be implemented are omitted or throw PlatformNotSupportedException. Some behaviours need opting in per endpoint, for example request buffering ([PreBufferRequestStream]) or HttpContext.Current itself, because they cost performance.

3. Remote app session in detail

  1. A request hits an endpoint marked with [Session] (or .RequireSystemWebAdapterSession()).
  2. The Core app calls the Framework app's session endpoint with the user's session cookie and the API key.
  3. The Framework app loads the session (locking it if the request is not read-only) and returns the serialised values.
  4. The handler runs; on completion, changes are posted back and the lock is released.

Because values cross processes, each key needs a serialiser (RegisterKey<T>("CartId") with JSON, or a custom ISessionKeySerializer). Classic ASP.NET session is exclusive per session for writable requests, so parallel requests from the same user queue; mark read-only endpoints as such.

4. Remote authentication in detail

The Core app registers a remote authentication handler. When it needs the user, it forwards the relevant headers and cookies to the Framework app's authenticate endpoint. The Framework app runs its own pipeline (Forms auth, OWIN cookies, Windows auth) and returns the serialised ClaimsPrincipal, or a redirect/401 which the Core app relays. Logging in still happens on the Framework app until you move it.

5. Security

  • The API key must be long, random and stored as a secret (Key Vault), not in config files in git.
  • Run the remote endpoints over HTTPS, ideally only reachable on a private network (VNet integration, private endpoints), so the session endpoint isn't exposed to the internet.
  • Session data may include personal information; under the Privacy Act 1988 it is still personal data in transit and needs the same protection.

6. Removing them

Track how many requests use remote session and remote auth (custom metrics). When the login flow and session-heavy pages have moved, switch to a shared cookie or an identity provider, move session to Redis or remove it, then delete the remote features. When the last shared library no longer needs System.Web types, refactor them to HttpContext or plain parameters and drop the package.

Try it yourself

  1. Create a Framework MVC app and an ASP.NET Core 10 app with YARP, and configure remote authentication; check User.Identity.Name in a Core endpoint.
  2. Add remote session with one registered key and measure added latency with Application Insights dependencies.
  3. Fire two parallel writable requests from one browser and observe session locking.
  4. Move one shared library from System.Web to the adapters package and multi-target it.
  5. Replace remote authentication with a shared cookie using Data Protection and compare latency.

💻 Code

The Framework 4.8 app exposes session and authentication to the new app (Global.asax.cs):

// ASP.NET Framework 4.8 app
protected void Application_Start()
{
    SystemWebAdapterConfiguration.AddSystemWebAdapters(this)
        .AddJsonSessionSerializer(options =>
        {
            // Every session key the new app reads must be registered with its type
            options.RegisterKey<int>("CartId");
            options.RegisterKey<string>("PreferredBranch");
        })
        .AddRemoteAppServer(options =>
            options.ApiKey = ConfigurationManager.AppSettings["RemoteAppApiKey"]) // from a secret store at deploy time
        .AddSessionServer()
        .AddAuthenticationServer();
}

The ASP.NET Core 10 app is the front door, with YARP and the remote clients:

// Program.cs (ASP.NET Core 10)
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSystemWebAdapters()
    .AddJsonSessionSerializer(options =>
    {
        options.RegisterKey<int>("CartId");
        options.RegisterKey<string>("PreferredBranch");
    })
    .AddRemoteAppClient(options =>
    {
        options.RemoteAppUrl = new Uri(builder.Configuration["ReverseProxy:Clusters:legacy:Destinations:app:Address"]!);
        options.ApiKey = builder.Configuration["RemoteAppApiKey"]!; // Key Vault via managed identity
    })
    .AddSessionClient()
    .AddAuthenticationClient(isDefaultScheme: true);

builder.Services.AddReverseProxy().LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
builder.Services.AddControllersWithViews();

var app = builder.Build();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSystemWebAdapters();

app.MapDefaultControllerRoute();
// Unmigrated routes go to the Framework app
app.MapReverseProxy();
app.Run();

A migrated controller that needs the legacy session and user:

namespace Contoso.Shop.Web.Controllers;

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SystemWebAdapters;

[Authorize]
public sealed class CartController(ICartService carts) : Controller
{
    // Only endpoints that need session pay for the remote call; read-only avoids the session lock
    [Session(IsReadOnly = true)]
    public async Task<IActionResult> Index(CancellationToken ct)
    {
        System.Web.HttpContext legacy = HttpContext; // implicit conversion to the adapter type
        var cartId = legacy.Session?["CartId"] as int?;
        if (cartId is null) return RedirectToAction("Empty");

        var cart = await carts.GetAsync(cartId.Value, User.Identity!.Name!, ct);
        return View(cart);
    }
}

public interface ICartService { Task<CartView> GetAsync(int cartId, string userName, CancellationToken ct); }
public sealed record CartView(int Id, IReadOnlyList<string> Lines);

⚠ Common mistakes

  • Mistake: Treating the adapters as a full System.Web. Why it is wrong: only a subset of APIs is implemented; some members throw PlatformNotSupportedException. Instead: compile shared libraries against the adapters early and fix what's missing.
  • Mistake: Turning on remote session for every endpoint. Why it is wrong: every request pays an HTTP round trip and may take the session lock. Instead: opt in per endpoint and mark read-only ones IsReadOnly = true.
  • Mistake: Forgetting to register session keys. Why it is wrong: unregistered keys can't be serialised, so values are missing or throw. Instead: register every key with its type on both apps, and keep the lists identical.
  • Mistake: Storing the API key in web.config or appsettings.json in git. Why it is wrong: anyone with the key can read users' session data. Instead: keep it in Key Vault and rotate it; restrict the endpoints to the private network.
  • Mistake: Exposing the Framework app publicly as well as through YARP. Why it is wrong: users can bypass the new front door and its security headers. Instead: make the legacy app reachable only from the Core app.
  • Mistake: Keeping the adapters indefinitely. Why it is wrong: permanent coupling and latency to an app you meant to retire. Instead: track usage and plan to replace them with a shared cookie, an identity provider and a distributed store.
  • Mistake: Storing large object graphs in session. Why it is wrong: every remote session call serialises them, adding latency and memory. Instead: store ids in session and load data from the database.

🏛 Senior insight: trade-offs

The adapters let you decouple the order of migration from the dependencies between features: you can move the cart page before the login page. That flexibility is worth a few milliseconds per request in the early months. The senior job is to keep them temporary: put the exit in the plan, measure how many requests depend on them, and move identity to the long-term solution (often Entra ID or Entra External ID) as its own increment.

Measure it like any dependency. Application Insights records each remote session and authentication call as a dependency, so you can chart added latency per route, calls per request and failure rate; watch session lock waits and CPU/memory on the Framework app, which now serves extra internal traffic. Each route switch goes through CI with integration and Playwright end-to-end tests, and is controlled by YARP config or a feature flag so it can be reversed in minutes. The API key lives in Key Vault, accessed with managed identity, and is rotated on a schedule.

This overlaps with the strangler fig at the architecture level (Phase 15) and YARP (Phase 18); here the focus is the mechanics that make a route-by-route move work.

Approach When it fits Cost When not to
Remote auth + remote session Early, legacy login and session-heavy pages Latency per request, coupling Long term
Shared cookie (Data Protection) Both apps use cookie auth Shared key ring management Windows auth or custom auth schemes
Distributed session store Session data is simple and serialisable Change legacy session provider Session holds live objects
Identity provider (Entra ID) Target architecture Bigger change, user migration Need to move fast on day one

🔗 Follow-ups the interviewer may ask

  1. When: Candidate talks about the YARP routing side of the migration Why: Checks they can configure YARP and a backend-for-frontend around the migration
    How to answer

    For a strangler-fig migration, I put a new ASP.NET Core 10 app in front of the legacy ASP.NET Framework 4.8 app. Routes the new app implements are served locally; everything else is forwarded to the legacy app with YARP's MapForwarder as a lowest-priority catch-all. I migrate one vertical slice at a time, using System.Web adapters to share session and authentication, until the legacy app has no traffic and is switched off. Rollback is a route change.

    For a backend-for-frontend, the SPA authenticates with an HttpOnly, SameSite cookie to the BFF; the BFF holds the OAuth tokens and attaches access tokens server-side when YARP forwards calls to the APIs, so no token ever reaches browser JavaScript.

    The risks are extra latency, shared state coupling the two apps, CSRF on cookie-based calls, and the "temporary" proxy becoming permanent, so I set exit criteria up front.

  2. When: Candidate suggests moving session to a distributed store instead Why: Checks how they would move Framework session state first
    How to answer

    In-process session lives in the w3wp.exe memory, so users are pinned to one server (sticky sessions) and lose state on every app pool recycle. Switch <sessionState mode="SQLServer"> or a Redis provider (for example Azure Cache for Redis) so session survives recycles and works across servers, which improves availability and lets you scale out. This forces session objects to be serialisable and adds a store round trip per request, which flushes out large or non-serialisable objects: measure session size and trim it. It also prepares the migration: ASP.NET Core has no in-process Session by default, its session sits on IDistributedCache, and the System.Web adapters' remote session lets a new ASP.NET Core app read the legacy app's session during an incremental, page-by-page move so users don't notice the switch.

  3. When: Candidate starts describing the overall migration plan Why: Checks the broader strangler-fig plan: slicing, data and measuring progress
    How to answer

    I wouldn't rewrite it. I'd use the strangler fig pattern: put a new ASP.NET Core 10 app in front, with YARP proxying every route it doesn't handle yet to the old .NET Framework 4.8 app. Then I move features route by route, starting with slices that are valuable and loosely coupled, while the team keeps shipping.

    The tricky parts are shared state: I use System.Web adapters to share authentication and session between the two apps, multi-target shared libraries to .NET Standard 2.0, and keep one database until the code has moved, so I'm never migrating code and data in the same step.

    I measure progress by the percentage of traffic served by the new app, legacy code deleted, and error rate and p95 per migrated route, with a flag to send a route back.

    The trade-off: running two apps for a while costs effort, but every step is small and reversible.

🛠 Real-world problems: how you handle them

Remote session locks make the new dashboard slower than the old one
Situation
An [insurance broker portal] was migrating from MVC 5 to ASP.NET Core 10 with YARP and System.Web adapters. The new dashboard fires [six] parallel AJAX calls. [About 3,000] brokers log in daily.
Signals
After the dashboard moved, Application Insights showed p95 rising from [800 ms] to [2.6 s]; the dependency map showed the remote session endpoint called six times per page, the calls running one after another.
Investigation
Traced one page load end to end: each AJAX endpoint was marked `[Session]` (writable), so the Framework app's session lock serialised them. Only one endpoint actually wrote to session.
Resolution
Immediate: marked five endpoints `[Session(IsReadOnly = true)]`, bringing p95 back to [900 ms]. Real fix: moved the dashboard's data out of session into a per-user cache keyed by user id, and removed session from those endpoints entirely.
Prevention
Code review rule: `[Session]` must state read-only or writable with a reason; a custom metric counting remote session calls per request; load test with parallel requests per user before switching routes.

How to tell it (STAR)

**S:** We were migrating [a broker portal] route by route with YARP and System.Web adapters. **T:** The newly migrated dashboard was three times slower than the old one, and I owned the investigation. **A:** Using Application Insights' end-to-end trace, I saw six remote session calls running one after another: every endpoint was marked as writing to session, so the legacy session lock serialised them. I marked five as read-only the same day, then moved that data out of session entirely. **R:** p95 went from [2.6 s] to [700 ms], below the old app, and we added a review rule and a metric so remote session usage stayed visible until we removed it [four months later].

More in Migration Topics

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me