Code review of a typical problematic controller: catch-all returning 200 with exception messages (information disclosure, broken HTTP semantics, swallowed errors), over-posting by binding EF entities, mass assignment of sensitive fields, hand-rolled validation, sync-over-async and missing cancellation, and a rewrite with request DTOs, validation, ProblemDetails, proper status codes and global exception handling.
Ranked by severity: (1) over-posting: binding the EF entity lets a client set fields they shouldn't (IsApproved, Role, Price, Id, navigation properties), a security hole. (2) information disclosure: returning ex.Message can leak SQL, server names or personal data. (3) broken HTTP semantics: 200 with success: false makes failures look like successes to monitoring, retries, caches and clients. (4) swallowed exceptions: the catch-all hides bugs and usually doesn't log. (5) hand-rolled validation: inconsistent and duplicated. The rewrite: a request DTO with only the allowed fields, DataAnnotations with [ApiController] (or FluentValidation), explicit mapping to the entity, proper status codes (201, 400, 404, 409) via ProblemDetails, and global exception handling with UseExceptionHandler instead of try/catch in every action.
"I'd rank the findings by impact: security first, then wrong data and wrong behaviour, then diagnostics, then design.
The most serious problem is binding the EF entity straight from the body. That's over-posting, or mass assignment: the client can send
isApproved: true, a differentcustomerId, a lowerprice, or even nested navigation objects that EF will happily insert. It's an OWASP API Top 10 issue. Second iserror = ex.Message: exception messages from EF and SqlClient can contain table names, constraint names, server names and even data values, which is an information disclosure and, if personal data is involved, an APP 11 concern. Third, returning 200 for failures breaks everything that relies on status codes: Application Insights shows a 100% success rate during an outage, clients and gateways don't retry, and caches may store the error. Fourth, the catch-all swallows every exception, usually without logging, so bugs disappear. Fifth, the hand-writtenifvalidation duplicates what[ApiController]and DataAnnotations do, and it's inconsistent between actions.For example, [at company] I reviewed [a claims endpoint] like this and found that [a partner could approve its own claims] by adding one property to the JSON. We fixed it the same day with a DTO. The rewrite I'd propose: a
CreateClaimRequestrecord with only the fields a client may set and validation attributes;[ApiController]so invalid input returns a 400 automatically; explicit mapping to the entity where server-owned fields are set by the server;CreatedAtActionon success,NotFound,ValidationProblemor 409 for known failures; and no try/catch in the action, becauseUseExceptionHandlerwithAddProblemDetailslogs and returns a safe 500 with a trace id. The rule I close the review with: never bind what you persist, never return what you catch."
[Route("api/claims")]
public class ClaimsController : Controller // 6. Controller (views), no [ApiController]
{
private readonly AppDbContext _db;
public ClaimsController(AppDbContext db) => _db = db;
[HttpPost]
public IActionResult Create([FromBody] Claim claim) // 1. EF entity bound from the body (over-posting)
{
try
{
if (claim.Amount <= 0) // 5. hand-rolled, inconsistent validation
return Ok(new { success = false, error = "Amount must be positive" }); // 3. 200 for a failure
if (string.IsNullOrEmpty(claim.PolicyNumber))
return Ok(new { success = false, error = "Policy required" });
_db.Claims.Add(claim);
_db.SaveChanges(); // 7. sync I/O, no CancellationToken
return Ok(new { success = true, data = claim }); // 8. returns the entity (leaks internal fields)
}
catch (Exception ex) // 4. swallows everything, no logging
{
return Ok(new { success = false, error = ex.Message }); // 2. leaks internals; 3. 200 again
}
}
}
| # | Severity | Finding | Impact |
|---|---|---|---|
| 1 | Security | Over-posting via entity binding | Clients set IsApproved, Status, CustomerId, nested entities |
| 2 | Security | ex.Message returned |
Leaks SQL, constraint names, data; aids attackers |
| 3 | Wrong behaviour | 200 for failures | Monitoring blind, no retries, caching of errors |
| 4 | Diagnostics | Catch-all, no logging | Bugs hidden; outages invisible |
| 5 | Wrong data | Hand-rolled validation | Rules differ between actions; easy to miss fields |
| 6 | Design | Controller without [ApiController] |
No automatic 400, binding inference, ProblemDetails |
| 7 | Scalability | SaveChanges() sync, no CancellationToken |
Blocks threads; work continues after client leaves |
| 8 | Security/design | Entity returned in response | Leaks internal fields and couples clients to the schema |
See the code example: a DTO with only client-owned fields, validation attributes, [ApiController], explicit mapping, async EF calls with CancellationToken, CreatedAtAction with a response DTO, and global exception handling.
Domain.Entities namespace; UseExceptionHandler + AddProblemDetails confirmed in Program.cs; an analyser rule against catch (Exception) without rethrow or logging in controllers.After replacing entity binding with DTOs across [25] endpoints and moving error handling to UseExceptionHandler, Application Insights' failed-request rate went from a misleading 0% to a real 0.4%, which exposed a recurring database timeout that had been hidden for months behind success: false responses.
Checks whether the candidate can spot security and correctness problems quickly, rank them, and propose an idiomatic rewrite.
Green flags
ex.Message as information disclosure.[ApiController], ProblemDetails and global exception handling.Red flags
Model binding sets every public settable property that appears in the JSON. With an entity:
POST /api/claims
{ "policyNumber": "P-1", "amount": 100, "isApproved": true, "status": "Paid",
"customer": { "id": 0, "name": "New customer" } }
EF Core's Add tracks the whole graph: isApproved and status are saved, and the nested customer with id: 0 is inserted as a new row. [Bind] include lists and [BindNever] exist but are fragile (a new property is bindable by default). DTOs make the allowed surface explicit.
ex.Message is dangerousExamples of real messages: Cannot insert duplicate key row in object 'dbo.Customers' with unique index 'IX_Customers_Email'. The duplicate key value is ([email protected]) (leaks schema and personal data); A network-related or instance-specific error occurred... server: sql-prod-aue-01 (leaks infrastructure). OWASP's 'Improper error handling' and the Privacy Act's APP 11 both apply.
| Component | Relies on status codes for |
|---|---|
| Application Insights / Azure Monitor | Failure rate, alerts, availability |
Polly / Microsoft.Extensions.Http.Resilience |
Retry on 5xx/408/429 |
| API gateways, CDNs | Caching (200s are cacheable) |
| Clients and SDKs | Exceptions vs success paths |
UseExceptionHandler + IExceptionHandler centralises logging (with trace id), mapping of known exceptions to 409/404, and a safe generic 500. Local try/catch is right only when you can actually handle the exception: retry, compensate, or translate a specific exception like DbUpdateConcurrencyException into a domain outcome.
[ApiController] + DataAnnotations reject invalid input before the action; business rules (does the policy exist and is it active?) belong in the application layer and return ValidationProblem or 409 with the same error shape.
isApproved: true property to the original action and query the database.id: 0 and watch EF insert it.ex.Message returned.The rewrite: request and response DTOs, validation, explicit mapping, async EF with cancellation, proper status codes and global error handling.
// Features/Claims/ClaimsController.cs
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Claims.Api.Features.Claims;
// Only the fields a client is allowed to set
public sealed record CreateClaimRequest(
[Required, RegularExpression(@"^P-\d{6}$")] string PolicyNumber,
[Range(0.01, 1_000_000)] decimal Amount,
[Required, StringLength(2000)] string Description);
// Only the fields a client is allowed to see
public sealed record ClaimResponse(int Id, string PolicyNumber, decimal Amount, string Status, DateTimeOffset LodgedAt);
[ApiController] // automatic 400 ValidationProblemDetails, binding inference
[Route("api/claims")]
public sealed class ClaimsController(AppDbContext db, TimeProvider clock) : ControllerBase
{
[HttpPost]
[ProducesResponseType<ClaimResponse>(StatusCodes.Status201Created)]
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<ClaimResponse>> Create(CreateClaimRequest request, CancellationToken ct)
{
// Business rule: needs data, same error contract as input validation
var policyActive = await db.Policies.AnyAsync(p => p.Number == request.PolicyNumber && p.IsActive, ct);
if (!policyActive)
{
ModelState.AddModelError(nameof(request.PolicyNumber), "No active policy with this number.");
return ValidationProblem(ModelState);
}
// Explicit mapping: server-owned fields are set by the server, never by the client
var claim = new Claim
{
PolicyNumber = request.PolicyNumber,
Amount = request.Amount,
Description = request.Description,
Status = ClaimStatus.Lodged,
IsApproved = false,
LodgedBy = User.Identity?.Name ?? "unknown",
LodgedAt = clock.GetUtcNow()
};
db.Claims.Add(claim);
await db.SaveChangesAsync(ct); // no try/catch: UseExceptionHandler logs and returns a safe 500
var response = new ClaimResponse(claim.Id, claim.PolicyNumber, claim.Amount, claim.Status.ToString(), claim.LodgedAt);
return CreatedAtAction(nameof(Get), new { id = claim.Id }, response);
}
[HttpGet("{id:int}")]
public async Task<ActionResult<ClaimResponse>> Get(int id, CancellationToken ct)
=> await db.Claims.Where(c => c.Id == id)
.Select(c => new ClaimResponse(c.Id, c.PolicyNumber, c.Amount, c.Status.ToString(), c.LodgedAt))
.SingleOrDefaultAsync(ct) is { } claim ? claim : NotFound();
}
// Program.cs: errors handled once, for every endpoint
using Claims.Api;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddProblemDetails(o => o.CustomizeProblemDetails = ctx =>
ctx.ProblemDetails.Extensions["traceId"] = System.Diagnostics.Activity.Current?.Id ?? ctx.HttpContext.TraceIdentifier);
builder.Services.AddExceptionHandler<DbConflictExceptionHandler>(); // e.g. unique index -> 409 with a safe message
builder.Services.AddSingleton(TimeProvider.System);
var app = builder.Build();
app.UseExceptionHandler(); // logs the exception; client gets ProblemDetails with a trace id, no internals
app.UseStatusCodePages();
app.MapControllers();
app.Run();
[Bind("...")] include lists as the fix. Why it is wrong: Easy to forget when properties are added, and doesn't help with JSON bodies in the same way. Instead: DTOs.IsApproved property on the DTO or entity is mapped automatically, reintroducing over-posting, and reflection-based mappers hide errors until runtime. Instead: Map by hand or use a source-generated mapper (Mapperly) with unmapped-member warnings as errors.ex.Message to clients. Why it is wrong: Information disclosure of schema, infrastructure and personal data. Instead: Safe messages and a trace id; log the details.success: false. Why it is wrong: Monitoring, retries and caches treat failures as success. Instead: Proper status codes with ProblemDetails.catch (Exception) in every action. Why it is wrong: Swallows bugs, duplicates logic, and often skips logging. Instead: UseExceptionHandler + IExceptionHandler; catch only what you can handle, such as DbUpdateConcurrencyException mapped to 409.db.Update(entity)). Why it is wrong: Every column is overwritten, including ones the client never saw, and concurrent edits are lost silently. Instead: Load the entity, apply allowed changes from an update DTO, and use a rowversion concurrency token.A senior reviewer ranks findings by impact and separates blocking issues from suggestions, then fixes the class of problem, not just the instance: an architecture test that forbids entities in API contracts, global exception handling configured once, and a checklist item for status codes. The framework already provides the safe defaults ([ApiController], ProblemDetails, UseExceptionHandler); the review's job is to make sure the code uses them instead of reinventing worse versions.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Request/response DTOs | Every endpoint | Mapping code | Never skip on writes |
[Bind] / [BindNever] |
Legacy MVC forms you can't refactor yet | Fragile | New code |
| Global exception handling | Every service | One-time setup | n/a |
| Local try/catch | Specific, handleable exceptions (concurrency, retries) | Some code | Catch-all wrappers |
| Architecture tests (NetArchTest, ArchUnitNET) | Teams that want rules enforced | Small test project | Tiny codebases |
ProblemDetails is the standard JSON shape for HTTP API errors, defined by RFC 9457 (which replaced RFC 7807): type, title, status, detail, instance, plus extension members, served as application/problem+json. ValidationProblemDetails adds an errors dictionary per field. In ASP.NET Core, AddProblemDetails() registers IProblemDetailsService, which the framework uses wherever it writes an error body: UseExceptionHandler for unhandled exceptions, UseStatusCodePages for empty 404s/401s, and the developer exception page. CustomizeProblemDetails adds a traceId and anything else to every response; an IExceptionHandler maps known exceptions to specific codes with a stable errorCode extension. The trade-off: one consistent contract for every error, but you must make sure no internal detail leaks.
The code shows the classic problems: throw ex destroys the stack trace; catching Exception and returning null swallows real failures; logging ex.Message loses the chain; catch-log-rethrow at every layer duplicates logs; .Result blocks and wraps errors in AggregateException; async void crashes the process; throwing Exception gives callers nothing to catch; clean-up outside finally leaks the lock; exceptions used for control flow (parse in try/catch); and cancellation logged as an error. The rewrite uses async Task all the way, using/finally for clean-up, Try methods for expected failures, a specific domain exception with an inner exception, filters for transient retries, and one global handler that logs once.
How to tell it (STAR)
**S:** In a code review of our [claims API] I found the create action bound the EF entity directly, and [a partner] had been setting `isApproved` on its own claims. **T:** I needed to close the hole immediately and fix the underlying pattern. **A:** I shipped a same-day DTO fix, worked with the business to reverse the approvals, then removed the catch-all that returned 200 with exception messages, added `[ApiController]`, ProblemDetails and global exception handling, and wrote an architecture test banning entities in API signatures. **R:** The over-posting path was closed within [hours], our failure rate became visible for the first time and exposed a hidden timeout, and the architecture test has blocked [two] similar attempts since.
Last updated 23 Nov 2026.