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.
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.
"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 [anIndexOutOfRangeException] and once corrupted the list. I framed it as 'this will behave differently on each server and isn't thread-safe; could we useIMemoryCacheor 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: readingHttpContext.Currentinside 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."
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();
}
}
| # | 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." |
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.
using on connection and reader.HttpContext.Current, SELECT *, idempotency, tracked on the migration board.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.
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
Red flags
SELECT *web.config is enoughA 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
List<T>.AddRange isn't atomic. Two requests writing at once can corrupt the internal array or throw.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.
| 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.
status = x' OR '1'='1 against a test database and see every row returned; then parameterise it._recent.AddRange from 50 parallel tasks and observe exceptions or wrong counts.WebApplicationFactory test for the authorised path.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();
}
}
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.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 |
Ranked by severity:
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.int.Parse throws when DI resolves the service, and a singleton holding an open SqlConnection leaks and breaks pooling.AppConfig.Config hides dependencies, is null before start-up, pollutes parallel tests and never reloads.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.
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.
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.
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.
Last updated 23 Nov 2026.