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

📚 Interview question

How do ASP.NET MVC 5 and Web API 2 differ from ASP.NET Core? Explain System.Web, Global.asax, HttpContext.Current and web.config, and what replaces each of them in .NET 10.

Covers the classic ASP.NET stack (System.Web, IIS integrated pipeline, Global.asax, HttpModules, HttpContext.Current, web.config, separate MVC and Web API) and the ASP.NET Core equivalents (Program.cs, middleware, IHttpContextAccessor, appsettings.json, unified MVC).

Junior Theory Intermediate aspnet-core aspnet-mvc5 configuration legacy-migration system-web web-api-2

🎯 Key points

  • System.Web.dll ties classic ASP.NET to IIS and Windows
  • MVC 5 and Web API 2 were separate frameworks with different base classes, filters and DI hooks; Core has one, plus API-specific [ApiController] and minimal APIs
  • Global.asax Application_Start becomes Program.cs; HttpModules and HttpHandlers become middleware
  • HttpContext.Current (ambient static) becomes HttpContext passed in, or IHttpContextAccessor used sparingly
  • web.config appSettings and connectionStrings become appsettings.json plus environment variables and the options pattern
  • Built-in DI with constructor injection; MVC 5 needed Unity, Autofac or Ninject
  • Kestrel is the built-in server; IIS hosts it in-process (IIS HTTP server) or as a reverse proxy via the ASP.NET Core Module
  • Synchronous I/O is disallowed by default, so I/O must be async end to end

⏱ 30-second answer

Classic ASP.NET sits on System.Web.dll, which is bound to IIS and Windows. MVC 5 and Web API 2 were two separate frameworks: different controller base classes (Controller vs ApiController), filters, routing and DI hooks. App start-up lived in Global.asax, cross-cutting code in HttpModules, request data came from the ambient HttpContext.Current, and settings came from web.config.

ASP.NET Core replaces all of that: one MVC framework for pages and APIs, Program.cs for start-up, middleware for modules, HttpContext passed explicitly (or IHttpContextAccessor), appsettings.json plus environment variables via the options pattern, and built-in DI. The trade-off: it is faster and cross-platform, but nothing in System.Web compiles against it unchanged.

🗣 Full answer (senior)

How I would answer this in an interview

"Classic ASP.NET is built on System.Web.dll, which is basically the IIS integrated pipeline exposed to .NET. Everything hangs off it: HttpApplication and Global.asax for start-up and app events, HttpModules for things like authentication and logging, HttpHandlers for endpoints, and HttpContext.Current, a static property that gives any code anywhere the current request. Configuration is web.config: XML that mixes app settings, connection strings, IIS settings and assembly binding redirects.

On top of that sat two frameworks. MVC 5 for HTML, with Controller in System.Web.Mvc, and Web API 2 for JSON, with ApiController in System.Web.Http. They looked similar but had separate routing, filters, model binding and dependency resolvers, so registering a filter in one didn't apply to the other. DI wasn't built in; you plugged in Autofac or Unity.

ASP.NET Core merges MVC and Web API into one framework, and replaces each piece. Program.cs replaces Global.asax. Middleware replaces modules and handlers. appsettings.json, environment variables and the options pattern replace web.config app settings. DI is built in. And HttpContext is passed to you: in a controller it's a property, and anywhere else you inject IHttpContextAccessor. The mistake I see is treating IHttpContextAccessor as a drop-in for HttpContext.Current and injecting it everywhere, which drags request state into business logic. Better to pass the values you need, like the user ID, as parameters. The senior line: System.Web is not a library you can upgrade, it's the platform, so a migration replaces the hosting model, not just the code."


Concept mapping

Classic ASP.NET (System.Web) ASP.NET Core (.NET 10)
Global.asax Application_Start Program.cs top-level statements
HttpModule (BeginRequest, AuthenticateRequest) Middleware (app.Use...)
HttpHandler (.ashx) Endpoint (app.MapGet) or controller action
HttpContext.Current HttpContext parameter / ControllerBase.HttpContext / IHttpContextAccessor
web.config <appSettings>, <connectionStrings> appsettings.json, environment variables, user secrets, Key Vault, IOptions<T>
ConfigurationManager.AppSettings["Key"] IConfiguration["Key"] or bound IOptions<T>
System.Web.Mvc.Controller + System.Web.Http.ApiController One Microsoft.AspNetCore.Mvc.ControllerBase / Controller
GlobalFilters and config.Filters (two sets) One filter pipeline, plus endpoint filters for minimal APIs
DependencyResolver.SetResolver(...) builder.Services built-in container
Session on by default (in-proc) Session opt-in, backed by IDistributedCache
Runs inside IIS (w3wp.exe) Runs on Kestrel; IIS in-process or as reverse proxy via ANCM

Things that behave differently

Area Classic Core
Synchronous I/O Allowed Blocked by default on Kestrel (AllowSynchronousIO = false)
Request body Can be read many times Forward-only stream; call EnableBuffering() to re-read
JSON Newtonsoft.Json System.Text.Json (case-sensitive by default outside MVC, different date handling)
Bundling System.Web.Optimization Build-time tooling or MapStaticAssets

Production example

When a team I would describe as typical moves a Web API 2 service to ASP.NET Core, the most common surprises are JSON differences (property casing, DateTime format, reference loops) and HttpContext.Current returning null in background code. Catching those needs contract tests that compare old and new responses byte for byte; a service with 120 endpoints commonly finds 5–10 that serialise differently.

🔍 What the interviewer is checking

Checks that the candidate can map classic ASP.NET concepts to ASP.NET Core and knows why it is a new hosting model, not an upgrade.

Green flags

  • Explains System.Web is tied to IIS
  • Knows MVC 5 and Web API 2 were separate and merged in Core
  • Maps Global.asax, modules, HttpContext.Current and web.config correctly
  • Mentions JSON and synchronous I/O differences

Red flags

  • Thinks you can "upgrade" MVC 5 by changing the target framework
  • Suggests injecting IHttpContextAccessor everywhere without caveats
  • Puts secrets in appsettings.json

📚 Learn in depth

1. What System.Web actually is

System.Web.dll is the managed half of the IIS integrated pipeline. IIS raises events for every request, and HttpApplication exposes them to .NET:

IIS (w3wp.exe)
  └─ HttpApplication (Global.asax)
       BeginRequest → AuthenticateRequest → AuthorizeRequest →
       ResolveRequestCache → AcquireRequestState (Session) →
       [HttpHandler executes: MvcHandler / Web API / Page] →
       ReleaseRequestState → EndRequest
       (HttpModules subscribe to any of these events)

Because this is IIS-shaped, it can't run on Linux or in Kestrel, and it can't be split into a NuGet package. That is why ASP.NET Core is a new framework rather than a new version.

2. HttpContext.Current

HttpContext.Current reads the context from the current logical call context. In classic ASP.NET it flows across await only when the app runs with the task-friendly SynchronizationContext (<httpRuntime targetFramework="4.5" /> or later). On a raw thread-pool thread or Task.Run without that context, it is null. It is global state: any class can reach it, which makes code hard to test.

ASP.NET Core removed the static. IHttpContextAccessor stores the context in an AsyncLocal<T>, so it flows with async code, but it is only valid while the request runs. Capturing it in a background task and reading it later gives a disposed or recycled context.

3. web.config versus the configuration system

web.config is XML read by ConfigurationManager. It contains app settings, IIS settings (<system.webServer>), runtime binding redirects and sometimes secrets. Changing it restarts the app domain.

ASP.NET Core configuration is a stack of providers, later ones winning:

appsettings.json → appsettings.{Environment}.json → user secrets (dev)
  → environment variables → command line → (Azure App Configuration / Key Vault)

Values are bound to typed classes with IOptions<T>, validated at start-up with ValidateOnStart(), and can reload without restarts via IOptionsMonitor<T>. When hosted in IIS, a small web.config still exists, but only to configure the ASP.NET Core Module.

4. Two frameworks become one

MVC 5 and Web API 2 had duplicate abstractions:

Concern MVC 5 Web API 2
Base class System.Web.Mvc.Controller System.Web.Http.ApiController
Result ActionResult IHttpActionResult / HttpResponseMessage
Filters System.Web.Mvc.IActionFilter System.Web.Http.Filters.IActionFilter
DI hook DependencyResolver HttpConfiguration.DependencyResolver

ASP.NET Core has one of each. [ApiController] adds the API behaviours (automatic 400 for invalid models, binding source inference).

Try it yourself

  1. Create an MVC 5 project in Visual Studio (if you have the .NET Framework workload) and list the events in Global.asax.cs and web.config sections; map each to its ASP.NET Core equivalent.
  2. In a .NET 10 app, write middleware that logs request duration and compare it with an HttpModule's BeginRequest/EndRequest.
  3. Call HttpContextAccessor.HttpContext inside Task.Run after the request has finished and observe it is null or invalid.
  4. Bind a section of appsettings.json to a record with ValidateDataAnnotations().ValidateOnStart() and start the app with a missing value.
  5. Serialise the same object with Newtonsoft.Json defaults and System.Text.Json web defaults and diff the output.

💻 Code

Classic Web API 2 controller and its ASP.NET Core equivalent.

// Before: Web API 2 on .NET Framework 4.8
using System.Configuration;
using System.Web;
using System.Web.Http;

public class InvoicesController : ApiController
{
    [HttpGet, Route("api/invoices/{id:int}")]
    public IHttpActionResult Get(int id)
    {
        var userId = HttpContext.Current.User.Identity.Name;          // ambient static
        var maxDays = int.Parse(ConfigurationManager.AppSettings["InvoiceMaxDays"]); // web.config
        // ... load invoice ...
        return Ok(new { id, userId, maxDays });
    }
}
// After: ASP.NET Core on .NET 10
namespace Billing.Api;

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

public sealed record InvoiceOptions
{
    public int MaxDays { get; init; } = 30;
}

[ApiController]
[Route("api/invoices")]
public sealed class InvoicesController(IOptions<InvoiceOptions> options) : ControllerBase
{
    [HttpGet("{id:int}")]
    public IActionResult Get(int id, CancellationToken ct)
    {
        var userId = User.Identity?.Name;   // HttpContext.User, passed in, no static
        return Ok(new { id, userId, options.Value.MaxDays });
    }
}
// Program.cs replaces Global.asax and the configuration parts of web.config
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOptions<InvoiceOptions>()
    .Bind(builder.Configuration.GetSection("Invoice"))
    .ValidateOnStart();
builder.Services.AddControllers();

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
// appsettings.json replaces <appSettings> in web.config
{
  "Invoice": { "MaxDays": 30 }
}

⚠ Common mistakes

  • Mistake: Replacing every HttpContext.Current with an injected IHttpContextAccessor. Why it is wrong: It keeps request state leaking into business logic and breaks in background work. Instead: Read what you need in the controller and pass plain values (user ID, tenant) down.
  • Mistake: Copying secrets from web.config into appsettings.json in git. Why it is wrong: Secrets end up in source control. Instead: Use user secrets locally and Key Vault or environment variables in Azure.
  • Mistake: Assuming JSON output stays the same. Why it is wrong: System.Text.Json differs from Newtonsoft.Json in casing, dates, enums and reference handling. Instead: Write contract tests or use AddNewtonsoftJson() temporarily.
  • Mistake: Porting HttpModules as MVC filters. Why it is wrong: Filters only run for MVC endpoints, not static files or other endpoints. Instead: Port modules to middleware in the right order.
  • Mistake: Doing synchronous reads of the request body. Why it is wrong: Kestrel throws by default because synchronous I/O blocks thread-pool threads. Instead: Use async APIs.
  • Mistake: Thinking ASP.NET Core can't run on IIS. Why it is wrong: It runs in IIS through the ASP.NET Core Module, in-process or out-of-process. Instead: Keep IIS if ops needs it and plan Linux later.

🏛 Senior insight: trade-offs

The big idea is that classic ASP.NET is a platform (IIS plus System.Web) and ASP.NET Core is a library you host. That's why migration feels like moving house, not repainting. Merging MVC and Web API didn't remove API-specific features: [ApiController] gives automatic 400 ProblemDetails responses and binding-source inference, and minimal APIs are a lighter option for pure HTTP APIs. Built-in constructor injection replaces DependencyResolver and service-locator calls, so controllers declare their dependencies and can be unit tested by passing fakes. Because synchronous I/O is blocked by default, data access and outbound calls need to become async as part of the move. For large apps, Microsoft's System.Web adapters let you keep using familiar HttpContext shapes in shared libraries while you move controllers across, and contract tests that compare old and new responses catch JSON and status-code drift.

Approach When it fits Cost When not to
Port controllers straight to ASP.NET Core Small API, good tests Low to medium Lots of System.Web in shared libraries
System.Web adapters plus incremental move Large MVC 5 app, shared libraries use HttpContext Medium, temporary shims New greenfield code
Keep Newtonsoft.Json during migration Many clients depend on exact JSON Small perf cost After contracts are pinned with tests

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions middleware replacing HttpModules Why: Checks they understand middleware order and Use/Run/Map
    How to answer

    Middleware is a component in the request pipeline: a RequestDelegate that receives the HttpContext, can do work, calls next to pass the request on, and can do more work when the response comes back. It can also short-circuit by not calling next. Use adds middleware that may call next; Run adds terminal middleware; Map branches the pipeline by path; UseWhen branches on a condition and rejoins, MapWhen branches without rejoining. Because each middleware wraps the next, order is behaviour: exception handling first, then HTTPS, static files, routing, CORS, authentication, authorisation and finally endpoints. Custom middleware can be convention-based (a class with InvokeAsync, created once as a singleton) or implement IMiddleware (resolved from DI per request). The trade-off: convention-based is the fastest default; IMiddleware is clearer when you need scoped dependencies.

  2. When: Candidate mentions Program.cs replacing Global.asax Why: Checks they know what the Generic Host sets up
    How to answer

    The Generic Host (IHost) is the common runtime shell for every modern .NET app, web or worker: it owns configuration, logging, dependency injection and the application lifetime. WebApplication.CreateBuilder(args) creates one with sensible defaults: appsettings.json, appsettings.{Environment}.json, user secrets in Development, environment variables and command-line args; console, debug and EventSource logging; and Kestrel. Build() freezes the service collection and builds the IServiceProvider. Run() starts hosted services, then the web server, and blocks until shutdown. On SIGTERM or Ctrl+C the host fires ApplicationStopping, stops accepting requests, lets in-flight ones finish, stops hosted services and exits within HostOptions.ShutdownTimeout (30 seconds by default). The trade-off: the defaults are great, but you must understand them to override them deliberately.

  3. When: Candidate mentions IHttpContextAccessor as the replacement for HttpContext.Current Why: Checks they understand the request lifetime and AsyncLocal flow
    How to answer

    IHttpContextAccessor stores the current context in an AsyncLocal, so it flows with the request's async calls and is valid only while the request runs. Fire-and-forget work, Task.Run that outlives the request, or a singleton reading it later can see null or a recycled context from another request, because HttpContext objects are pooled. HttpContext is also not thread-safe: reading or writing it from parallel tasks, even during the request, can race and corrupt state. Don't capture scoped services (like a DbContext) either; they are disposed when the request scope ends. Instead, copy the values you need (user ID, correlation ID, tenant) into a message or parameters before starting the work, create a new DI scope in the background worker, and use a queue (Channel<T> with a BackgroundService) for anything that must outlive the request.

↩ Usually asked after

More in Legacy Technologies

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me