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

📚 Interview question

Code review: a legacy Web API 2 OrdersController reads the user from HttpContext.Current, keeps a static list of recent orders, builds SQL by string concatenation over a synchronous SqlConnection, and reads a payment gateway key from web.config appSettings. What do you flag, ranked by severity, and what does the .NET 10 rewrite look like?

A senior code review of legacy Web API 2 code: secrets in web.config, SQL injection, thread-unsafe static state, HttpContext.Current coupling, undisposed connections and synchronous I/O, with a ranked list of findings, kind review comments, and the ASP.NET Core rewrite using DI, options, Key Vault and async parameterised data access.

Senior CodeReview Advanced aspnet-core code-review legacy-migration secrets-management sql-injection web-api-2

🎯 Key points

  • Security first: SQL injection from concatenated SQL, live payment key in web.config committed to git
  • Rotate the leaked key and treat it as an incident, not just a code change
  • Static List<T> is shared mutable state: race conditions, no eviction so unbounded growth, lost on recycle, different per server; remove it or use a bounded cache with expiry (IMemoryCache SizeLimit) or a distributed cache
  • SqlConnection not disposed on exceptions leads to pool exhaustion; synchronous I/O blocks thread-pool threads
  • HttpContext.Current couples data access to the request and is null on background threads
  • Phased plan: small security patch on .NET Framework now, covered by characterisation tests; structural rewrite in the .NET 10 migration
  • Rewrite: DI, IOptions plus Key Vault via managed identity, parameterised async queries, User from ControllerBase, no shared mutable state
  • Close with blocking vs suggested comments, analysers (CA2100, CA2000), secret scanning and a checklist

⏱ 30-second answer

Rank by impact. Blocking, security: SQL built by string concatenation is SQL injection, and the payment gateway key in web.config is a live secret in source control: rotate it and move it to Key Vault. Blocking, correctness: a static List<T> shared across requests is not thread-safe, grows forever, and differs per server. Reliability: an undisposed SqlConnection leaks the pool; synchronous I/O blocks threads. Design: HttpContext.Current inside data code couples it to the request and breaks in background work.

The .NET 10 rewrite: constructor DI, IOptions<T> bound from Key Vault via managed identity, User from ControllerBase, parameterised async queries in a repository, and no shared mutable state. The trade-off: fix security now in place; do the structural rewrite as part of the migration.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd rank by what can hurt us most, and I'd write the comments so the author can act on them without feeling attacked. Top of the list are two security issues: the query concatenates the customer filter straight into SQL, which is textbook SQL injection, and there's a live payment gateway key in web.config, which is in git. The second one isn't a code comment, it's an incident: the key has to be rotated today because everyone with repo access, and every backup of the repo, has it.

For example, at [company] I reviewed [a similar controller] where [a static list] was used as a 'recent orders' cache. It worked on the developer's machine, but in production there were [two servers], so users saw different results on each refresh, and under load a List<T> being written by two requests at once threw [an IndexOutOfRangeException] and once corrupted the list. I framed it as 'this will behave differently on each server and isn't thread-safe; could we use IMemoryCache or just query the database?' and paired with the author on it. That change removed [a recurring error] from the logs.

Then reliability: the connection isn't in a using, so any exception leaks it, and the calls are synchronous, which ties up threads. And design: reading HttpContext.Current inside the data method means it can't be tested and will be null if it's ever called from a background job. The mistake I see in reviews like this is rewriting everything in one PR. I'd block on the injection and the secret, fix them in place on .NET Framework now, and do the structural changes as part of the .NET 10 migration. Senior line: secure it today, modernise it on purpose."


Code under review

public class OrdersController : ApiController
{
    private static List<Order> _recent = new List<Order>();                           // 1

    [HttpGet, Route("api/orders")]
    public IHttpActionResult Get(string status)
    {
        var user = HttpContext.Current.User.Identity.Name;                            // 2
        var conn = new SqlConnection(
            ConfigurationManager.ConnectionStrings["Shop"].ConnectionString);          // 3
        conn.Open();                                                                  // 4
        var cmd = new SqlCommand(
            "SELECT * FROM Orders WHERE UserName = '" + user +
            "' AND Status = '" + status + "'", conn);                                  // 5
        var reader = cmd.ExecuteReader();                                             // 6
        var orders = new List<Order>();
        while (reader.Read())
            orders.Add(new Order { Id = (int)reader["Id"], Total = (decimal)reader["Total"] });
        conn.Close();
        _recent.AddRange(orders);                                                     // 7
        return Ok(orders);
    }

    [HttpPost, Route("api/orders/{id}/pay")]
    public IHttpActionResult Pay(int id)
    {
        var key = ConfigurationManager.AppSettings["PaymentGatewayKey"];             // 8
        var client = new PaymentClient(key);                                          // 9
        client.Charge(id);                                                            // 10
        return Ok();
    }
}

Findings, ranked by severity

# Severity Finding Comment to the author
5 Critical (security) SQL injection via status (and user) "Blocking: status comes from the query string, so ' OR 1=1 -- returns everyone's orders. Could we use SqlParameters? Happy to pair."
8 Critical (security) Live payment key in web.config, committed "Blocking: this key is in git history. I've raised it with [security lead] to rotate today. Let's load it from Key Vault."
7, 1 High (wrong data, crash) Static List<Order> written by concurrent requests "Blocking: List<T> isn't thread-safe, grows without limit and is different on each server. What do we need 'recent' for? Maybe a query or IMemoryCache."
3, 4, 6 High (stall) Connection and reader not disposed on exception "Wrap in using so an exception doesn't leak the connection and exhaust the pool."
10 Medium (stall) Synchronous I/O to SQL and the payment gateway "Suggestion: async methods free threads while waiting; important once we're on ASP.NET Core."
9 Medium (reliability) PaymentClient created per call; no timeout or idempotency "Can we register the client once and pass an idempotency key so a retry doesn't double-charge?"
2 Low (design) HttpContext.Current in the action "Suggestion: use User on the controller and pass the user ID down; easier to test."
— Low (design) SELECT *, no authorisation attribute, no paging "Nit: select only needed columns; add [Authorize]; page results."

The rewrite

See the code example: an ASP.NET Core controller with constructor injection, [Authorize], a repository using parameterised async queries, payment options from Key Vault through managed identity, and no static state.

How I'd close the review

  • Blocking: SQL injection, the secret (plus rotation as an incident under the team's security process, and a check of whether it was misused), the static list.
  • Should fix in this PR: using on connection and reader.
  • Suggestions / follow-up ticket: async, HttpContext.Current, SELECT *, idempotency, tracked on the migration board.
  • Automate it: enable CA2100 (SQL injection review), CA2000 (dispose), secret scanning with push protection in the repository, and a PR checklist item for secrets and parameters.

Production example

In reviews of legacy controllers like this, the injection and secret findings are fixed in a same-day patch on .NET Framework, while the structural rewrite ships later with the .NET 10 migration. Splitting it this way keeps the risky change small: the security patch is typically under 30 lines and can be tested in an afternoon.

🔍 What the interviewer is checking

Checks that the candidate can review legacy code by real impact, communicate kindly and specifically, and plan a safe path to .NET 10.

Green flags

  • Puts SQL injection and the leaked secret first, and treats the secret as an incident needing rotation
  • Explains why the static list is wrong (threads, growth, web farm)
  • Separates blocking from suggested comments
  • Fixes security in place and defers the structural rewrite
  • Adds analysers and secret scanning to prevent recurrence

Red flags

  • Starts with naming or SELECT *
  • Thinks deleting the key from web.config is enough
  • Insists on a full rewrite before merging a security fix

📚 Learn in depth

1. Why severity ordering matters

A review comment list with 15 items of equal weight gets the easy ones fixed and the important ones argued over. Ordering by impact (security hole or crash → wrong data → stalls → diagnostics → design) tells the author what must happen before merge and what can be a follow-up.

Critical  ─ exploitable now (injection, leaked secret)          → block, fix today
High      ─ wrong data or outage under load (races, leaks)     → block
Medium    ─ degraded performance/reliability (sync I/O)        → fix in PR or ticket
Low       ─ maintainability (HttpContext.Current, SELECT *)    → suggestion

2. The static list in detail

  • List<T>.AddRange isn't atomic. Two requests writing at once can corrupt the internal array or throw.
  • Nothing removes items, so memory grows until the app pool recycles (see the IIS memory question).
  • On a web farm each server has its own list, so results depend on which server answered.
  • On recycle it's emptied. Static mutable state is effectively a cache with no rules.

3. Leaked secrets are incidents

Removing the key from web.config in a new commit doesn't remove it from git history, forks, CI logs or developer laptops. The only real fix is rotation. Under the Notifiable Data Breaches scheme, a leaked payment credential that could lead to serious harm needs assessment, so involve whoever owns security. Prevention: Key Vault with managed identity (no secret in config at all), and secret scanning with push protection.

4. Mapping to ASP.NET Core

Legacy .NET 10
ApiController ControllerBase + [ApiController]
HttpContext.Current.User User property (ClaimsPrincipal)
ConfigurationManager.AppSettings IOptions<PaymentOptions> bound from config + Key Vault
new SqlConnection in action Repository registered in DI, Microsoft.Data.SqlClient, await using
new PaymentClient(key) Typed HttpClient via IHttpClientFactory with timeout and resilience handler
Static list IMemoryCache with limits, or no cache

On .NET Framework you can still apply most fixes: parameters, using, MemoryCache, and config builders that read secrets from Key Vault or environment variables instead of web.config.

Try it yourself

  1. Run the original query with status = x' OR '1'='1 against a test database and see every row returned; then parameterise it.
  2. Write a test that calls _recent.AddRange from 50 parallel tasks and observe exceptions or wrong counts.
  3. Turn on CA2100 and CA2000 in a project and see what they flag.
  4. Enable secret scanning on a test repo and commit a fake key pattern to see push protection block it.
  5. Port the controller to ASP.NET Core and write a WebApplicationFactory test for the authorised path.

💻 Code

The .NET 10 rewrite with DI, options from Key Vault, parameterised async data access and no shared state.

// Program.cs
using Azure.Identity;
using Shop.Api;

var builder = WebApplication.CreateBuilder(args);

// Secrets come from Key Vault via managed identity: nothing secret in appsettings.json or git
builder.Configuration.AddAzureKeyVault(
    new Uri(builder.Configuration["KeyVault:Uri"]!), new DefaultAzureCredential());

builder.Services.AddOptions<PaymentOptions>()
    .Bind(builder.Configuration.GetSection("Payment"))
    .ValidateDataAnnotations()
    .ValidateOnStart();

builder.Services.AddScoped<IOrderRepository, SqlOrderRepository>();
builder.Services.AddHttpClient<IPaymentClient, PaymentClient>(c => c.Timeout = TimeSpan.FromSeconds(10));
builder.Services.AddControllers();
builder.Services.AddAuthentication().AddJwtBearer();
builder.Services.AddAuthorization();

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
// OrdersController.cs
namespace Shop.Api;

using System.ComponentModel.DataAnnotations;
using System.Data;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;

public sealed record OrderDto(int Id, decimal Total, string Status);

public sealed class PaymentOptions
{
    [Required] public string GatewayKey { get; init; } = "";
}

public interface IOrderRepository
{
    Task<IReadOnlyList<OrderDto>> GetForUserAsync(string userName, string status, CancellationToken ct);
}

public interface IPaymentClient
{
    Task ChargeAsync(int orderId, string idempotencyKey, CancellationToken ct);
}

public sealed class PaymentClient(HttpClient http, Microsoft.Extensions.Options.IOptions<PaymentOptions> options)
    : IPaymentClient
{
    public async Task ChargeAsync(int orderId, string idempotencyKey, CancellationToken ct)
    {
        using var request = new HttpRequestMessage(HttpMethod.Post, $"charges/{orderId}");
        request.Headers.Add("Authorization", $"Bearer {options.Value.GatewayKey}");
        request.Headers.Add("Idempotency-Key", idempotencyKey);   // retries can't double-charge
        using var response = await http.SendAsync(request, ct);
        response.EnsureSuccessStatusCode();
    }
}

public sealed class SqlOrderRepository(IConfiguration config) : IOrderRepository
{
    public async Task<IReadOnlyList<OrderDto>> GetForUserAsync(string userName, string status, CancellationToken ct)
    {
        await using var conn = new SqlConnection(config.GetConnectionString("Shop"));
        await conn.OpenAsync(ct);
        await using var cmd = new SqlCommand("""
            SELECT TOP (100) Id, Total, Status FROM dbo.Orders
            WHERE UserName = @user AND Status = @status
            ORDER BY Id DESC
            """, conn);
        cmd.Parameters.Add("@user", SqlDbType.NVarChar, 256).Value = userName;  // parameters: no injection
        cmd.Parameters.Add("@status", SqlDbType.VarChar, 20).Value = status;

        var result = new List<OrderDto>();
        await using var reader = await cmd.ExecuteReaderAsync(ct);
        while (await reader.ReadAsync(ct))
            result.Add(new OrderDto(reader.GetInt32(0), reader.GetDecimal(1), reader.GetString(2)));
        return result;
    }
}

[ApiController]
[Authorize]
[Route("api/orders")]
public sealed class OrdersController(IOrderRepository orders, IPaymentClient payments) : ControllerBase
{
    [HttpGet]
    public async Task<ActionResult<IReadOnlyList<OrderDto>>> Get([FromQuery] string status, CancellationToken ct) =>
        Ok(await orders.GetForUserAsync(User.Identity!.Name!, status, ct)); // User from the controller, no static

    [HttpPost("{id:int}/pay")]
    public async Task<IActionResult> Pay(int id, [FromHeader(Name = "Idempotency-Key")] string idempotencyKey,
        CancellationToken ct)
    {
        await payments.ChargeAsync(id, idempotencyKey, ct);
        return Accepted();
    }
}

⚠ Common mistakes

  • Mistake: Listing findings in file order instead of severity. Why it is wrong: The author fixes nits and argues about the injection. Instead: Rank by impact and mark what blocks the merge.
  • Mistake: Treating the leaked key as a code fix only. Why it is wrong: It stays in git history, forks and backups. Instead: Rotate it, check for misuse, and move it to Key Vault.
  • Mistake: Replacing the static List<T> with a ConcurrentBag and moving on. Why it is wrong: It is thread-safe but still unbounded, per-server and lost on recycle. Instead: Question whether the cache is needed; use a bounded cache with expiry, a distributed cache, or the database.
  • Mistake: "Escaping" quotes in the concatenated SQL. Why it is wrong: Escaping is error-prone and still creates a plan per value. Instead: Use parameters.
  • Mistake: Changing legacy code without tests around it. Why it is wrong: The security patch can silently change results, and the later rewrite has nothing to compare against. Instead: Add characterisation tests (an integration test per endpoint against a test database, plus a test that the injection payload returns nothing) before the patch, and reuse them against the .NET 10 version.
  • Mistake: Demanding the full ASP.NET Core rewrite in the same PR. Why it is wrong: It turns a small security fix into a large risky change and competes with the team's planned work. Instead: Patch security in place; schedule the rewrite as a migration slice sized to the team's capacity.
  • Mistake: Writing comments like "this is terrible code". Why it is wrong: It makes the author defensive and slows the fix. Instead: State the problem, its impact and a suggested fix, and offer to pair.

🏛 Senior insight: trade-offs

A legacy code review is triage. The code has probably run for years, so the question is not "is it modern?" but "what can hurt customers or the business, and what's the smallest safe change?". Security and data-integrity findings get fixed now on the current stack; the structural move to .NET 10 is planned work with its own tests. The tone matters as much as the content: the author may have inherited this code.

Finding type Fix now (on .NET Framework) Fix in migration Why
SQL injection, leaked secret Yes — Exploitable today
Static shared state Yes (bounded cache or remove) — Wrong data and crashes
Undisposed connections Yes — Outages under load
Synchronous I/O Optional Yes Matters most on ASP.NET Core
HttpContext.Current, DI Partial Yes Structural, needs the new host

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions moving secrets out of configuration Why: Checks depth on secrets, the options pattern and start-up validation
    How to answer

    Ranked by severity:

    1. Committed live secrets (SMTP password, sk_live_ Stripe key). Treat this as an incident: rotate first, then move the values to Key Vault with managed identity. Deleting the file doesn't remove them from git history.
    2. Constructors doing work: int.Parse throws when DI resolves the service, and a singleton holding an open SqlConnection leaks and breaks pooling.
    3. A static AppConfig.Config hides dependencies, is null before start-up, pollutes parallel tests and never reloads.
    4. No validation, so bad values fail on a live request.

    The rewrite uses options classes with BindConfiguration and ValidateOnStart, Key Vault for secrets, passwordless Entra ID auth to SQL, and connections opened per operation. The trade-off: a little more set-up, in exchange for secure, testable, fail-fast configuration.

  2. When: Candidate mentions introducing DI into the legacy app Why: Checks they can introduce DI incrementally without a big-bang rewrite
    How to answer

    I'd use a strangler approach, not a rewrite. First, characterisation tests around the code I'll touch first. Then a single composition root (the Generic Host in modern .NET, or ServiceCollection built in the old entry point) and a bridge: the legacy ServiceLocator.Get<T>() delegates to the real IServiceProvider, so old and new code share the same instances.

    From there I convert from the edges inwards: new code and any class I touch takes constructor dependencies; statics get thin adapters behind interfaces. I track locator call count as a metric and block new usages with an analyser.

    The trade-off: for months the codebase is half old, half new, which is uglier than a rewrite plan but keeps shipping.

  3. When: Candidate mentions HttpContext.Current and web.config replacements Why: Checks they can map classic ASP.NET concepts to ASP.NET Core
    How to 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.

🛠 Real-world problems: how you handle them

Security review of a legacy orders API before a PCI audit
Situation
A [retail] company's Web API 2 orders service on .NET Framework 4.8, running on [two] IIS servers, was due for a [PCI DSS / internal security] audit in [six weeks], with a .NET 10 migration planned for [next quarter].
Signals
A routine review found concatenated SQL, a payment gateway key in `web.config` committed to git, and a static list of recent orders. Logs showed intermittent `IndexOutOfRangeException` from the list [several times a week] and occasional connection pool timeouts.
Investigation
Ran secret scanning over the repository history and found the key in [14] commits; checked the gateway's dashboard for unexpected API usage. Enabled CA2100 and CA2000 to find other concatenated SQL and undisposed connections ([9] and [17] hits). Load-tested the endpoint to reproduce the list corruption and the pool exhaustion.
Resolution
Immediate: rotated the gateway key the same day, loaded the new one through a Key Vault config builder on .NET Framework, and shipped a patch that parameterised all flagged queries, wrapped connections in `using` and removed the static list. Real fix: the controller was rebuilt on ASP.NET Core with DI, options and async data access as the first slice of the .NET 10 migration.
Prevention
Secret scanning with push protection on all repositories; CA2100 and CA2000 as errors; a PR checklist covering secrets, parameters and shared state; the security review added to the definition of done for migrated endpoints.

How to tell it (STAR)

**S:** We had a security audit in [six weeks] on an old Web API 2 orders service, and my review found SQL injection, a payment key in git and a thread-unsafe static list. **T:** I needed to close the risks fast without a risky rewrite before the audit. **A:** I raised the key as an incident and we rotated it the same day; I ran analysers to find every similar query and undisposed connection, and shipped a small patch on .NET Framework with parameters, `using` and the static list removed. I wrote the review comments as specific, blocking-versus-suggestion items and paired with the author. **R:** The audit found [no high findings] on that service, the intermittent exceptions and pool timeouts disappeared, and the same controller became the first slice of our .NET 10 migration.

More in Legacy Technologies

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me