CodeOath
← All posts
.NET Core / Web API70 min total · 19 parts

Building REST APIs with ASP.NET Core: Routing, Middleware, and Dependency Injection

Contents — Part 19 of 19: Common Mistakes Worth Remembering
Part 19 of 19 · ~1 min

Common Mistakes Worth Remembering

  • Registering a DbContext-consuming service as SingletonDbContext isn't thread-safe, and this breaks the moment two requests hit it concurrently.
  • The captive dependency bug: injecting a Scoped service into a Singleton, freezing that scoped instance for the app's entire lifetime instead of getting a fresh one per request.
  • Middleware order mistakes — authorization before authentication, or CORS registered too late in the pipeline to apply to a rejected request.
  • Blocking on async code with .Result/.Wait() instead of await, tying up thread pool threads (and, in some hosting contexts, risking a deadlock) that should have been freed during I/O.
  • Returning raw exceptions to the client instead of a proper ProblemDetails/error-handling middleware — leaks internal details and gives callers nothing structured to handle.
  • Putting business logic directly in the controller instead of behind an injected service interface — makes it untestable without spinning up the whole web pipeline, and couples HTTP concerns to domain logic.
  • Enabling AllowAnyOrigin() combined with AllowCredentials() (which the CORS spec itself disallows) or leaving permissive CORS configured in production after using it to silence a local development error.
  • Trying to bind two complex types from the request body on the same action — [ApiController] only infers one [FromBody] parameter per action.

See how ASP.NET Core's middleware pipeline compares to Express.js and Django's in Middleware Pipelines Compared, and revisit the value-type/reference-type and DbContext-lifetime reasoning underneath this whole stack in C# Fundamentals. Practice the underlying C# and API-design reasoning in the code lab.