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

πŸ“š Interview question

How does ASP.NET Web Forms work? Explain the page lifecycle, ViewState and postbacks, why teams loved it, the problems it causes, and why it has no direct successor in modern .NET.

Covers the Web Forms model: server controls, the page lifecycle events, ViewState and its size and security, postbacks and event handlers, why it suited desktop developers, and why Microsoft did not port it (Razor Pages and Blazor are the closest replacements).

Intermediate Theory Intermediate blazor legacy-migration page-lifecycle razor-pages viewstate web-forms

🎯 Key points

  • Web Forms imitates desktop event-driven programming over stateless HTTP
  • Page lifecycle: PreInit, Init, Load, postback events, PreRender, SaveStateComplete, Render, Unload
  • ViewState is a base64 hidden field, MAC-signed with the machine key, encrypted only if ViewStateEncryptionMode is set
  • Postbacks POST the form to the same page; UpdatePanel does partial updates but still runs the full server lifecycle
  • Problems: large pages, hard to test, code-behind mixes UI and logic, built-in controls dictate HTML unless you write custom controls
  • In-process Session and ViewState make pages stateful; move session to SQL Server or Redis to scale out
  • Built on System.Web, so not available in modern .NET
  • Replacements: Blazor (component and event model), Razor Pages (page-focused) or an SPA with an API

⏱ 30-second answer

Web Forms (2002) made web development feel like Windows Forms: drag server controls onto a page, double-click a button, write a Click handler in code-behind. It hides HTTP's statelessness with two tricks: postbacks (interactions POST the form back to the same page) and ViewState (a hidden field, signed by default and optionally encrypted, that carries control state between requests). Each request runs the page lifecycle: Init, Load, the postback event, PreRender, Render. UpdatePanel can make a postback update only part of the page, but the server still runs the whole lifecycle.

It is productive for forms-over-data apps, but pages get heavy, logic hides in code-behind and it is hard to test. It is built on System.Web, so it never came to modern .NET. Blazor is the closest in feel, Razor Pages the closest in structure, an SPA plus API another option. The trade-off: no tool converts it automatically; migration is page by page.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"Web Forms was Microsoft's way of bringing Windows Forms developers to the web. You drop server controls like asp:TextBox and asp:GridView on an .aspx page, and handle events like Button_Click in a code-behind class. HTTP is stateless, so it fakes state with two mechanisms. A postback: every button click submits the whole form back to the same URL. And ViewState: a hidden __VIEWSTATE field holding the serialised state of the controls, so the server can rebuild the page as it was and work out what changed.

On every request the page runs a fixed lifecycle. PreInit sets the master page and theme, Init creates controls, ViewState is loaded, Load runs, then the postback event handlers like Click and SelectedIndexChanged, then PreRender for final changes, ViewState is saved, and Render writes HTML. Most Web Forms bugs are lifecycle bugs: dynamic controls added in Load instead of Init lose their state, or data binding in Load without checking IsPostBack wipes the user's input.

The mistake I see is people dismissing Web Forms as bad. It shipped a huge number of internal business apps quickly. Its real problems are page weight from ViewState, logic buried in code-behind, poor testability and very little control over HTML. Microsoft didn't port it because it's built on System.Web and its abstractions fight the web. Blazor is the nearest replacement because it keeps components and event handlers; Razor Pages is nearest in structure, one page per URL. So my senior line is: you don't migrate Web Forms, you rebuild it page by page, and you pull business logic out of code-behind first."


The page lifecycle

Stage What happens Typical use
PreInit Master page, theme, dynamic controls created Set MasterPageFile
Init Controls initialised, IDs assigned Add dynamic controls here
Load ViewState / postback data Restore control state, apply posted values (framework)
Load Page and controls loaded Bind data if (!IsPostBack)
Postback events Click, TextChanged, SelectedIndexChanged Business actions
PreRender Last chance to change controls Final UI tweaks
SaveStateComplete ViewState saved (framework)
Render HTML written Custom rendering
Unload Clean-up Dispose resources

ViewState: what it costs

Aspect Detail
Format LosFormatter/ObjectStateFormatter serialised, base64 in __VIEWSTATE
Integrity MAC (HMAC) using the machine key; required since the 2014 security update
Confidentiality Not encrypted unless ViewStateEncryptionMode is set; never put sensitive data in it
Size A data-bound GridView can add 100 KB+ per page, sent both ways
Risk A leaked machine key lets attackers forge ViewState and get remote code execution

Where it went

Web Forms idea Modern equivalent
Server controls and events Blazor components and @onclick
.aspx page per URL Razor Pages .cshtml with a PageModel
Master pages Layouts (_Layout.cshtml)
User controls (.ascx) Partial views, view components, Blazor components
ViewState Explicit state: form fields, component state, query strings

Production example

A typical internal Web Forms app has screens with a GridView of 500 rows where ViewState alone is 300–400 KB, so every sort or page click uploads and downloads close to 1 MB. Turning EnableViewState="false" on read-only grids and paging in SQL commonly cuts page weight by over 70% without any migration at all.

πŸ” What the interviewer is checking

Checks that the candidate understands how Web Forms really works (lifecycle, ViewState, postbacks) and can reason about its migration fairly.

Green flags

  • Lists the lifecycle in the right order and knows the IsPostBack and dynamic-control traps
  • Explains ViewState is signed but not encrypted by default, and its size cost
  • Knows why it wasn't ported and names Blazor and Razor Pages as replacements
  • Suggests extracting logic before migrating

Red flags

  • Thinks ViewState is stored on the server
  • Believes there is an automatic converter to Blazor
  • Dismisses legacy apps without considering cost

πŸ“š Learn in depth

1. Stateful illusion over stateless HTTP

Browser                                  Server (IIS + System.Web)
  β”‚  GET /Orders.aspx                         β”‚
  │──────────────────────────────────────────▢│ build controls, bind data
  │◀── HTML + <input type=hidden __VIEWSTATE> β”‚ serialise control state
  β”‚                                           β”‚
  β”‚  user clicks "Save"                       β”‚
  β”‚  POST /Orders.aspx (all fields +          β”‚
  β”‚   __VIEWSTATE + __EVENTTARGET=btnSave)    β”‚
  │──────────────────────────────────────────▢│ rebuild controls (Init)
  β”‚                                           β”‚ load ViewState, apply posted values
  β”‚                                           β”‚ Load β†’ btnSave_Click β†’ PreRender
  │◀── full HTML page again                   β”‚ save ViewState, Render

Every interaction is a full round trip and a full re-render. UpdatePanel (ASP.NET AJAX) hides this by doing the same postback through XHR and replacing part of the page, but the server still runs the whole lifecycle.

2. How events are detected

The page compares posted values with ViewState values. If a TextBox value differs, it raises TextChanged. For buttons, the posted __EVENTTARGET names the control that caused the postback. This only works if the control tree is rebuilt identically on postback, which is why dynamic controls must be recreated in Init with the same IDs.

3. Why it was not ported

  • It depends on System.Web's HttpApplication, Page and handler model.
  • Control IDs, ViewState and the lifecycle assume one server-side page instance per request with full control over HTML generation.
  • Modern web design wants clean HTML, client-side interactivity, testable logic and stateless servers that scale out. Web Forms works against all four.

Microsoft's recommendation is to move to Blazor (closest model) or Razor Pages/MVC. Community projects such as an open-source Blazor component library that mimics Web Forms controls can reduce markup changes, but code-behind still needs rework.

4. Scale-out and session

Web Forms apps usually use in-process Session, which pins users to one server (sticky sessions) and loses state on app pool recycle. Moving session to SQL Server or Redis is a common first step before any migration, and it also exposes how much state the app keeps.

5. Security notes

  • ViewState must be MAC-protected (default now) and the machine key kept secret, especially on web farms where it is shared.
  • ValidateRequest blocks some HTML input, but it is not an XSS defence; encode output.
  • Event validation stops forged postback values for list controls.

Try it yourself

  1. Open the browser dev tools on a Web Forms page and measure the size of __VIEWSTATE before and after binding a grid.
  2. Decode a ViewState string with a ViewState decoder tool (on a test app only) and see what is stored.
  3. Add a dynamic control in Page_Load and then in Page_Init; observe state being lost in the first case on postback.
  4. Rebuild one Web Forms screen as a Blazor component and compare the number of lines of logic you could unit test.
  5. Set EnableViewState="false" on a read-only grid and confirm the page still works and is smaller.

πŸ’» Code

A Web Forms page and its Razor Pages equivalent on .NET 10.

// Before: Orders.aspx.cs (Web Forms code-behind)
public partial class Orders : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack) // without this, every postback rebinds and wipes user input
        {
            gridOrders.DataSource = OrderRepository.GetOpen(); // static data access in UI
            gridOrders.DataBind();
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        var id = int.Parse(txtOrderId.Text);
        OrderRepository.Cancel(id);           // business logic in the page
        lblMessage.Text = "Order cancelled";
    }
}
// After: Pages/Orders.cshtml.cs (Razor Pages, .NET 10)
namespace Shop.Web.Pages;

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

public sealed record OrderRow(int Id, string Customer, decimal Total);

public interface IOrderService
{
    Task<IReadOnlyList<OrderRow>> GetOpenAsync(CancellationToken ct);
    Task CancelAsync(int id, CancellationToken ct);
}

public sealed class OrdersModel(IOrderService orders) : PageModel
{
    public IReadOnlyList<OrderRow> Open { get; private set; } = [];

    [TempData] public string? Message { get; set; }

    public async Task OnGetAsync(CancellationToken ct) =>
        Open = await orders.GetOpenAsync(ct);        // explicit, no ViewState

    public async Task<IActionResult> OnPostCancelAsync(int id, CancellationToken ct)
    {
        await orders.CancelAsync(id, ct);            // logic lives in a testable service
        Message = "Order cancelled";
        return RedirectToPage();                     // Post/Redirect/Get avoids double submits
    }
}

⚠ Common mistakes

  • Mistake: Binding data in Page_Load without checking IsPostBack. Why it is wrong: Every postback rebinds and overwrites the user's input and selected rows. Instead: Bind on first load, or rebind deliberately after an action.
  • Mistake: Adding dynamic controls in Page_Load. Why it is wrong: ViewState is loaded before Load, so their state and events are lost. Instead: Create them in Init with stable IDs.
  • Mistake: Storing sensitive data in ViewState. Why it is wrong: ViewState is signed by default but only encrypted if you set ViewStateEncryptionMode, so by default anyone can decode it. Instead: Keep sensitive data on the server, or turn on encryption if it really must travel.
  • Mistake: Leaving ViewState on for every control. Why it is wrong: Pages grow to hundreds of KB and slow every postback. Instead: Disable it for read-only controls.
  • Mistake: Treating UpdatePanel as a performance fix. Why it is wrong: It still posts ViewState and runs the whole page lifecycle on the server; only the DOM update is partial. Instead: Reduce ViewState and server work, or call a small endpoint for the interactive part.
  • Mistake: Planning a tool-driven conversion of Web Forms. Why it is wrong: There is no automatic converter; the model is different. Instead: Extract logic from code-behind, then rebuild screens incrementally.
  • Mistake: Calling Web Forms worthless in an interview. Why it is wrong: It ran many profitable systems and the candidate may have to support one. Instead: Explain its strengths and its costs fairly.

πŸ› Senior insight: trade-offs

The key senior move with Web Forms is to separate the UI technology from the business logic. Most Web Forms apps have their rules spread through code-behind and static helpers. If you extract those into services (still on .NET Framework, behind interfaces, with tests), the same tested services can be reused by whichever new UI you choose, the move to Blazor, Razor Pages or an SPA needs less effort and carries less risk, and you can keep old screens running while new ones go live. Moving session to a distributed store (SQL Server or Redis) early also helps: it removes sticky sessions and lets an ASP.NET Core app share session during the transition.

Target When it fits Cost When not to
Blazor Server / Interactive Server Internal apps with event-heavy forms, team knows Web Forms Medium; needs SignalR connection per user Public sites needing SEO or offline use
Razor Pages Page-per-URL forms, simple interactions Medium; more rework of event logic Very interactive screens
SPA (React/Angular) + API Rich client, separate front-end team High; two codebases Small internal tool with a .NET-only team
Keep Web Forms, tidy up App is stable and nearing retirement Low Lots of new features planned

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate suggests Blazor Server as the replacement Why: Checks they understand Blazor Server's SignalR connection and its scaling cost
    How to answer

    SignalR is ASP.NET Core's real-time framework. A hub is a class whose public methods clients call, and the server calls methods on clients through Clients.All, Clients.Group(...) or Clients.User(...). Hubs are transient, created per invocation, so they hold no state. On connect the client calls negotiate and uses the best transport available: WebSockets, then Server-Sent Events, then long polling. Groups fan messages out to subsets of connections, but they live in memory, so a reconnecting client must re-join them (usually in OnConnectedAsync). Strongly typed hubs (Hub<IOrderClient>) replace method-name strings with an interface. Authentication uses the normal pipeline with [Authorize]. Browsers can't send an Authorization header on WebSockets or EventSource, so as a workaround the token travels as an access_token query parameter, read in JwtBearerEvents.OnMessageReceived.

    The trade-off: reconnects and routing come free, but every client holds a stateful connection that you must plan to scale.

  2. When: Candidate mentions Session or sticky sessions Why: Checks they know how state blocks scale-out and migration
    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.

↩ Usually asked after

More in Legacy Technologies

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me