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

📚 Interview question

Code review: a controller action wraps everything in try/catch and returns 200 with { success: false, error: ex.Message }, binds an EF Core entity directly from the request body and saves it, and validates fields by hand with if statements. What problems do you find, ranked by severity, and how would you rewrite it?

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.

Senior CodeReview Advanced aspnet-core code-review ef-core over-posting problem-details validation

🎯 Key points

  • Binding an EF entity allows over-posting/mass assignment: clients can set Id, Role, Price, IsApproved or navigation properties
  • Returning ex.Message leaks internals (SQL, connection details, personal data) and breaks APP 11 / OWASP guidance
  • 200 with success:false says 'processed successfully' while reporting failure: monitoring shows 0% errors, resilience handlers don't retry, gateways may cache it, clients take the success path
  • Catch-all swallows exceptions without logging and hides bugs; use global UseExceptionHandler + IExceptionHandler, which log every unhandled exception with the trace id
  • Hand-written validation is inconsistent and duplicates DataAnnotations/[ApiController] or FluentValidation
  • Rewrite: request DTO with only allowed fields, explicit mapping (by hand or a source-generated mapper such as Mapperly), proper status codes (201, 400, 404, 409) and ProblemDetails
  • Updates need concurrency control (rowversion, DbUpdateConcurrencyException mapped to 409) and partial-update DTOs rather than attaching a client-supplied entity
  • Async all the way (SaveChangesAsync with CancellationToken) so blocked threads don't starve the ThreadPool

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 different customerId, a lower price, or even nested navigation objects that EF will happily insert. It's an OWASP API Top 10 issue. Second is error = 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-written if validation 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 CreateClaimRequest record 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; CreatedAtAction on success, NotFound, ValidationProblem or 409 for known failures; and no try/catch in the action, because UseExceptionHandler with AddProblemDetails logs 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."


Code under review

[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
        }
    }
}

Findings ranked by severity

# 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

The rewrite

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.

How I'd close the review

  • Blocking: 1, 2, 3 and 4. Security and correctness; must be fixed before merge.
  • Should fix in this PR: 5, 6, 7 and 8, since the rewrite covers them naturally.
  • Follow-ups: a team checklist item 'no entities in request or response types'; an architecture test (NetArchTest) that fails if controller actions take or return types from the Domain.Entities namespace; UseExceptionHandler + AddProblemDetails confirmed in Program.cs; an analyser rule against catch (Exception) without rethrow or logging in controllers.

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can spot security and correctness problems quickly, rank them, and propose an idiomatic rewrite.

Green flags

  • Names over-posting/mass assignment as the top issue.
  • Flags ex.Message as information disclosure.
  • Explains why 200-for-errors breaks monitoring and retries.
  • Rewrites with DTOs, [ApiController], ProblemDetails and global exception handling.
  • Separates blocking from non-blocking comments.

Red flags

  • Focuses on naming and formatting.
  • Thinks the try/catch is good defensive coding.
  • Keeps returning entities.

📚 Learn in depth

1. Over-posting mechanics

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.

2. Why ex.Message is dangerous

Examples 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.

3. Status codes matter to infrastructure

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

4. Global exception handling vs try/catch

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.

5. Validation placement

[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.

Try it yourself

  1. Post an extra isApproved: true property to the original action and query the database.
  2. Post a nested navigation object with id: 0 and watch EF insert it.
  3. Force a unique index violation and read the ex.Message returned.
  4. Look at the failed-request rate in Application Insights for the original vs rewritten action under a forced failure.
  5. Write a NetArchTest rule that fails if an action parameter type lives in the entities namespace.

💻 Code

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();

⚠ Common mistakes

  • Mistake: Binding EF entities from request bodies. Why it is wrong: Over-posting lets clients set server-owned fields and insert related entities. Instead: Request DTOs with only allowed fields, mapped explicitly.
  • Mistake: Using [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.
  • Mistake: Replacing manual mapping with a convention-based mapper that maps every matching property. Why it is wrong: A new 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.
  • Mistake: Returning 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.
  • Mistake: 200 with success: false. Why it is wrong: Monitoring, retries and caches treat failures as success. Instead: Proper status codes with ProblemDetails.
  • Mistake: 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.
  • Mistake: Updating by attaching the client's object (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.
  • Mistake: Returning the entity in the response. Why it is wrong: Leaks internal fields, causes serialisation cycles and couples clients to the schema. Instead: Response DTOs, projected in the query.
  • Mistake: Reviewing only for style. Why it is wrong: The security and correctness issues matter far more than naming. Instead: Rank findings by severity and block merges on security and correctness.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate proposes replacing success:false with ProblemDetails. Why: Checks how to build a consistent ProblemDetails error contract for the rewrite.
    How to answer

    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.

  2. When: Candidate criticises the catch-all exception handling. Why: Checks a related review of exception-handling code and how to rank findings.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Partner able to approve its own claims through over-posting
Situation
A claims API [at company] exposed `POST /api/claims` to [about 15] broker partners. The action bound the EF `Claim` entity from the body and wrapped everything in try/catch returning 200.
Signals
A reviewer noticed claims with `IsApproved = true` and no approver recorded; Application Insights showed a 0% failure rate even during a known database outage; a support ticket contained a SQL unique-index error message copied from the API response.
Investigation
Queried claims approved without an approval audit record ([n] found, from [one] partner); replayed a request with an extra `isApproved` property in a test environment and confirmed it was persisted; reviewed responses for `ex.Message` content.
Resolution
Same-day hotfix replacing the entity parameter with a request DTO and setting server-owned fields on the server; reversed the improper approvals with the business; then removed the try/catch, added `[ApiController]`, ProblemDetails with trace ids and `UseExceptionHandler`, and changed failures to proper status codes.
Prevention
An architecture test forbidding entity types in controller signatures; a security review checklist for mass assignment; alerts on failed-request rate now that failures return real status codes; the incident assessed under the Notifiable Data Breaches scheme.

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.

↩ Usually asked after

More in Request Handling

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me