Skip to content

Traps — Things That Are Wrong In A Way That Sounds Right

← Roadmap · README

This is the highest signal-per-minute file in the repo. Every ⚠️ marker in the roadmap lands here, in one line each, with the correction.

Interviewers use these deliberately. A candidate who's read blog posts gives the plausible answer; a candidate who's shipped gives the correct one. That gap is the whole point of the question.

Read this twice the day before. Then once more in the morning.


Async and threading

⚠️ The plausible answer ✅ What's actually true Topic
"async makes code run on another thread" async/await is about not blocking a thread, not about using more of them. A truly async I/O call uses no thread while it waits. 2.11
".Result is fine if I know the task is done" In any context with a synchronization context it can deadlock, and in ASP.NET Core it blocks a thread-pool thread. Under load this cascades into thread-pool starvation. 2.13
"async void is fine for event handlers" It's tolerable for UI event handlers and wrong everywhere else — exceptions can't be caught by the caller and will crash the process. 2.15
"ConfigureAwait(false) is needed in ASP.NET Core" ASP.NET Core has no synchronization context, so it changes nothing in app code. It still matters in libraries, which may run on other platforms. 2.13

Dependency injection

⚠️ The plausible answer ✅ What's actually true Topic
"Scoped means one instance per class" Scoped means one instance per scope, which in a web app is one per HTTP request. Background services have no ambient scope — you must create one. 6.5
"Injecting a scoped service into a singleton is fine" The singleton captures that instance forever. Your DbContext becomes an app-lifetime object shared across all requests — non-thread-safe, leaking, and returning stale cached entities. 6.4
"Transient services are always safe" A transient in a singleton lives as long as the singleton — and ValidateScopes does not catch it, because that combination is technically legal. 6.4
"Scope validation protects me" It's Development-only by default. The environment that would catch the bug is the one you never deploy. Enable it everywhere. 6.13
"DI is the same as the Dependency Inversion Principle" DI is how you receive a dependency; dependency inversion is what you depend on. And IoC is the broader principle both sit under. 6.1
"Every class should have an interface" An interface with one implementation and no test double is a file and an indirection buying nothing. Add it when you need to substitute. 6.1
"Registering the same interface twice replaces the first" Both stay — the collection is a list. A single resolve gives the last; IEnumerable<T> gives all. Duplicates change behaviour silently. 6.2
"GetService and GetRequiredService are interchangeable" GetService returns null, so a missing registration surfaces later as a null reference somewhere unrelated. 6.2
"Injecting IServiceProvider into a singleton lets me use scoped services" That's the root provider — the scoped service lives forever. Same bug, and validation misses it. Use IServiceScopeFactory. 6.5
"I created a scope, so I'm fine" Not if it's outside the loop. One DbContext for the service's whole lifetime is the captive dependency relocated. 6.5
"I can create a scope in my controller" The request already has one. A second scope means a second DbContext with its own change tracker and its own transaction. 6.5
"TryAdd is just a safer Add" With several implementations it silently skips all but the first. Use TryAddEnumerable. And it needs a separate using. 6.6
"Keyed services replace factories" Keys are fixed at registration. If the choice depends on runtime data like the current tenant, you still need a factory. 6.6
"The order of IEnumerable<T> doesn't matter" It's registration order, and it usually should matter — cheap checks before ones hitting a database or an API. But it's implicit and easy to break. 6.7
"A decorator is easy to register by hand" Register the inner service as the interface and the decorator resolves itself — infinite recursion. Register it as the concrete type. 6.8
"A factory registration is checked at startup" It runs lazily, on first resolution. A config error inside surfaces on the first request that needs it, not at startup. 6.8
"Ten constructor parameters? Inject IServiceProvider" That hides the smell rather than fixing it — and removes the only signal telling you the class does too much. Split it. 6.9
"The container disposes everything I give it" It disposes instances it created. Pass an already-constructed instance to AddSingleton(instance) and you own disposal. 6.10
"I should dispose the DbContext I injected" You didn't create it. Disposing it breaks every other service in that request sharing the same scope. 6.10
"A transient disposable is released when I finish with it" It's held by the scope until that scope ends. Resolving one in a loop means every instance stays open. 6.10
"IOptions<T> and IOptionsSnapshot<T> are interchangeable" IOptions<T> is singleton. IOptionsSnapshot<T> is scoped — a captive dependency in a singleton constructor. 6.13
"DateTime.UtcNow is fine, DI handles the rest" Time-dependent logic is then untestable or flaky. Inject TimeProvider (.NET 8+) and use FakeTimeProvider in tests. 6.12
"Unit tests need the DI container" They don't. The container composes the application; a unit test just news the class with fakes. Needing a container means it's an integration test. 6.12

Fundamentals and startup

⚠️ The plausible answer ✅ What's actually true Topic
"ASP.NET Core is ASP.NET with a new version number" It's a rewrite. System.Web doesn't exist, HttpContext.Current is gone, and Web Forms never ported. 4.1
"IIS hosts my ASP.NET Core app" The relationship inverted. Your app hosts Kestrel; IIS is a reverse proxy in front of it. 4.2
"Behind a load balancer I still see the client IP" You see the proxy's IP. You need UseForwardedHeaders, registered first, and only loopback proxies are trusted by default — so it works locally and silently fails in Kubernetes. 4.2
"UseHttpsRedirection is always correct" Behind a TLS-terminating proxy it causes an infinite redirect loop — the app sees http, redirects, the proxy forwards http again. 4.2
"Binding to localhost works in a container" The app starts, looks healthy, and refuses every external connection. Use http://+:8080. 4.2
"I can register a service anywhere in Program.cs" Not after builder.Build() — the collection is frozen. 4.3
"I can resolve DbContext from app.Services at startup" It's scoped and there's no ambient scope at startup. Call CreateScope() first. 4.3
"WebApplicationFactory<Program> just works" The generated Program is internal. Add public partial class Program { } or InternalsVisibleTo. 4.3
"Startup.cs implements an interface" It implements nothing — methods are found by name via reflection. Misspell ConfigureServices and it compiles and silently never runs. 4.4
"ValidateScopes protects me in production" It's Development-only by default, which is exactly why captive dependencies survive to production. 4.5
"IHostedService.StartAsync runs in the background" It blocks application startup. Slow work there delays readiness. Use BackgroundService.ExecuteAsync. 4.5
"Shutdown is fine by default" You get 5 seconds. Any request slower than that is cut off — on every deployment. 4.6
"Longer shutdown timeout is always safer" It must be shorter than the orchestrator's grace period, or Kubernetes SIGKILLs you mid-drain — and SIGKILL can't be caught. 4.6
"Kubernetes stops traffic before sending SIGTERM" Both happen at the same time and endpoint removal propagates asynchronously, so requests arrive after you've stopped accepting. Delay shutdown or fail readiness first. 4.6
"Environment.Exit shuts down cleanly" It skips every shutdown handler. Use lifetime.StopApplication(). 4.6
"No ASPNETCORE_ENVIRONMENT means Development" It defaults to Production — deliberately safe in deployment, confusing locally. 4.7
"The developer exception page is just verbose errors" It shows all environment variables in the browser — connection strings and API keys included. One stray ASPNETCORE_ENVIRONMENT=Development in prod exposes them. 4.7
"appsettings.production.json works fine" Environment names are case-insensitive in code, but file names are case-sensitive on Linux. That file is silently ignored. 4.7
"I set the environment in launchSettings.json" That file is never deployed. It has zero effect on production. 4.8
"In-process IIS hosting uses Kestrel" It uses IISHttpServer, a different implementation that talks to IIS directly. 4.9
"Static files respect [Authorize]" No. UseStaticFiles runs before authentication, so anything in wwwroot is downloadable by anyone with the URL. 4.10
"Put UseStaticFiles wherever" After authentication, every image runs JWT validation first. Forty assets = forty wasted auth cycles per page. 4.10
"The file is in wwwroot but returns 404" Unknown MIME types are not served by default. Register the extension rather than enabling ServeUnknownFileTypes. 4.10
"Clean Architecture is the professional choice" Four projects for six endpoints is cost with no benefit. Start with one project and folders; split when the pain is real. 4.11

Middleware and pipeline

⚠️ The plausible answer ✅ What's actually true Topic
"Middleware order doesn't really matter" UseAuthorization before UseAuthentication means User is never populated — the app silently 401s on everything, with no error. 5.2
"The pipeline is a list of steps" It's nested — each middleware wraps the rest, like try/finally. That's why await next() returns and lets you inspect the response. 5.1
"await next() hands off and finishes" It runs the entire remaining pipeline and waits. When it returns, the response already exists. 5.1
"My CORS policy is wrong" Often it's ordering. UseCors after UseAuthentication means the unauthenticated OPTIONS preflight is 401'd before CORS can answer. 5.2
"Map and UseWhen are interchangeable" Map is a dead end — the branch never rejoins, so MapControllers below never runs and every route 404s. UseWhen rejoins. 5.3
"app.Run(...) starts the app" app.Run() with no args does. app.Run(handler) adds terminal middleware — nothing after it ever executes. 5.3
"I can resolve a service once and capture it in my inline middleware" That pins one instance for the app's lifetime. Resolve from context.RequestServices inside the lambda. 5.4
"I can inject a scoped service into middleware's constructor" Conventional middleware is a singleton, created once. Scoped services go in the InvokeAsync parameters, or use IMiddleware. 5.5
"IOptions<T> and IOptionsSnapshot<T> are both fine in a middleware constructor" IOptions<T> is singleton and fine. IOptionsSnapshot<T> is scoped and must go in InvokeAsync. 5.5
"IMiddleware works like conventional middleware" It must be registered in DI yourself, or you get "No service for type..." on the first request. 5.6
"Returning early from middleware is enough" Without setting a status code you send an empty HTTP 200 — no error, nothing to debug from. 5.7
"Short-circuiting skips everything" Only what's below. Middleware above already called next and still runs its "after" half — which is why logging keeps working. 5.7
"I can keep a reference to HttpContext" It's pooled and reused after the response. A stored reference can end up pointing at another user's request. 5.8
"Modify the response after await next()" Headers are on the wire once the response has started. Use OnStarting, registered before next. 5.8
"I can read the request body in middleware and the controller still gets it" The body is forward-only and gets consumed — the action's model is null. Needs EnableBuffering() and Body.Position = 0. 5.9
"EnableBuffering() is enough" It only makes rewinding possible. Forgetting Position = 0 gives the exact same symptom as not buffering. 5.9
"UseHsts() is a good default everywhere" In development it can lock you out of http://localhost for months, across every project on that port. Production only. 5.10
"A 404 returns a JSON error body" A bare 404 from routing has an empty body unless you add UseStatusCodePages(). 5.11
"Returning ex.Message to the client is helpful" Exception messages routinely contain table names, file paths and connection details. Log the detail, return a trace ID. 5.11
"Registering IExceptionHandler is enough" Nothing runs without app.UseExceptionHandler(). No warning — exceptions just go unhandled. 5.12
"Handler registration order doesn't matter" They run in order until one returns true. A catch-all registered first makes every later handler unreachable. 5.12
"I'll validate the request model in middleware" Model binding hasn't run yet. Reading the body yourself also breaks binding downstream. Use a filter. 5.13
"I'll log requests in an action filter" Filters only run when a route matched — so you silently miss every 404, static file and rate-limited request. 5.13
"Logging the request is harmless" Headers carry Authorization and Cookie; query strings carry API keys and reset tokens. Log Path, not QueryString. 5.14
"Log everything at Information" Then the level conveys nothing and you can't alert. And EF Core at Information logs every SQL statement. 5.14

EF Core

⚠️ The plausible answer ✅ What's actually true Topic
"DbContext should be a singleton for performance" It is not thread-safe and its change tracker grows unbounded. Scoped is the correct lifetime; use AddDbContextPool if you want the pooling win. 13.2
".ToList() then filter — same thing" ToList() executes the query. Everything after it filters in memory after pulling the whole table across the wire. 13.10
"Lazy loading is convenient and harmless" It's the primary cause of N+1 queries, and it fires queries at serialization time, long after the context you expected. 13.9
"FromSqlRaw with string interpolation is fine" That's SQL injection. FromSqlInterpolated (or FromSqlRaw with parameters) parameterizes; FromSqlRaw($"...{x}") does not. 13.11
"AsNoTracking is a micro-optimization" On read-heavy endpoints returning many rows it's often a large win, and it prevents accidental updates. Default to it for reads. 13.7
"The InMemory provider is fine for testing" It doesn't enforce relational constraints, transactions, or SQL translation — tests pass that production fails. Use SQLite in-memory or Testcontainers. 13.20

.NET runtime and platform

⚠️ The plausible answer ✅ What's actually true Topic
".NET 4.8 is just an older .NET 8" Unrelated products. 4.8 is the final Windows-only Framework; 8 is the modern cross-platform one. The close numbers are why version 4 was skipped. 3.1
"The name 'Core' was dropped everywhere" The runtime dropped it; ASP.NET Core kept it. ASP.NET Core 10 runs on .NET 10. 3.1
"C# compiles to machine code" It compiles to IL. Machine code is produced later by the JIT, per method, on first call. 3.2
"CTS and CLS are the same thing" CTS is the full type system. CLS is the subset every .NET language supports — which is why C# allows Process() and process() but that isn't CLS-compliant. 3.2
"Benchmark the first few calls" Those measure Tier 0 unoptimised code plus the compilation itself. You must warm up first. 3.2
"Native AOT is just a faster build" It silently breaks reflection, Expression.Compile and Reflection.Emit. Compiles fine, fails at runtime. 3.2
"The GC frees everything eventually" It frees memory. File handles, sockets and DB connections need Dispose — the GC has no idea what they are. 3.3
"You can take a pointer to a managed array" Not without fixed. The GC moves objects during compaction and cannot update a raw pointer. 3.3
"The GC counts references" It uses reachability from roots, not counting. That's why circular references are collected fine. 3.4
"GC.Collect() will fix my memory usage" If the object is still reachable, no collection frees it. Forcing one triggers an expensive Gen 2 pass and promotes objects that would have died cheaply. 3.4
"Large objects are handled like any other" ≥ 85,000 bytes go to the LOH, collected only on Gen 2 and not compacted — so memory climbs from fragmentation with no actual leak. 3.4
"Server GC is strictly better" It uses one heap per core. In a small container that extra memory can breach the limit and get you OOM-killed. 3.4
"You can't leak memory in .NET" You can't forget to free — but you can keep a reference, which the GC must honour. Static collections, unremoved event handlers, captured closures. 3.5
"One memory dump will show the leak" One dump shows what's large. Two dumps minutes apart show what's growing, which is what you need. Then gcroot to find what holds it. 3.5
"IMemoryCache can't leak, it has eviction" Without an explicit SizeLimit it only evicts under memory pressure, which may arrive too late. 3.5
"Copy the DLL into the output folder and it'll load" The runtime resolves from deps.json, not by scanning folders. Not listed there = FileNotFoundException. 3.6
"Version conflicts fail the build" They fail at runtime with MethodNotFoundException. .NET picks the highest version and hopes it's compatible. 3.6
"#if NET8_0 covers .NET 8 and later" It's false once you add a net10.0 target. Use NET8_0_OR_GREATER. 3.7
"linux-x64 runs in any Linux container" Not Alpine. Alpine uses musl, so it needs linux-musl-x64. Fails at startup with a confusing missing-library error. 3.7
"dotnet build output is deployable" It isn't. publish gathers all dependencies plus deps.json and runtimeconfig.json. Build output may start, then fail on an uncopied package. 3.8
"netstandard2.1 is the better .NET Standard" .NET Framework never supported it, which removes the only reason to target Standard. Target net10.0 instead. 3.9
"STS releases are previews" They're full production releases. The only difference is 18 months of support versus 3 years. 3.10
"A newer .NET is always supported longer" .NET 7 (STS) went out of support before .NET 6 (LTS), despite shipping a year later. 3.10

Configuration and options

⚠️ The plausible answer ✅ What's actually true Topic
"I set it in appsettings.json, so that's the value" Later providers win. An environment variable set by the hosting platform silently overrides it. GetDebugView() shows which provider supplied each value. 7.1
"ConnectionStrings_Default sets the connection string" Nested keys need double underscores — ConnectionStrings__Default. A single one silently does nothing. 7.1
"Overriding an array in a later file replaces it" Arrays are indexed keys, merged per index. A 1-item override of a 3-item list leaves items 2 and 3 in place — a real problem for CORS origins. 7.2
"appsettings.production.json works fine" File names are case-sensitive on Linux. It's silently ignored when the environment is Production — and works on Windows. 7.2
"Only the active environment's JSON file is deployed" All of them ship in the published output, including the Development one. "It's only for dev" is not protection. 7.2
"User Secrets are encrypted" They're plain JSON in your user profile. The protection is being outside source control, not being secure at rest. 7.3
"CreateBuilder() is fine without args" That silently disables command-line configuration entirely. It compiles and runs. 7.3
"Environment variables are a fine place for production secrets" They're visible to the whole process, appear in crash dumps, and the developer exception page renders every one into the browser. 7.3
"Key Vault secrets use __ like environment variables" Double hyphen — Payments--ApiKey. That's a third escape convention after : and __. 7.4
"Rotated secrets are picked up automatically" Read once at startup unless you set a ReloadInterval — and even then IOptions<T> won't see the change. 7.4
"A missing config key throws" It returns null, and GetValue<int> returns 0. A missing batch size silently becomes zero. A malformed value does throw — inconsistently. 7.5
"I'll null-check GetSection" It never returns null — an absent section is an empty one. Use Exists() or GetRequiredSection. 7.5
"IOptionsSnapshot<T> is the modern IOptions<T>" It's scoped. In a singleton or conventional middleware that's a captive dependency — use IOptionsMonitor<T>. 7.6
"CurrentValue is safe to read repeatedly" It re-reads every access, so two reads in one method can return different objects. Capture it once per operation. 7.6
"required on an options property is enforced" The binder uses reflection, bypassing the compiler check. Use [Required] + ValidateOnStart. 7.7
"A typo in a config key will show up" Silent in both directions — an unmatched key is ignored, an unmatched property keeps its default. 7.7
"Positional records bind to configuration" No parameterless constructor, so they don't. Use a class with settable properties. 7.7
"ValidateDataAnnotations() fails the app at startup" Validation is lazy — it runs on first .Value access. ValidateOnStart() is the line that matters. 7.8
"[Required] catches a missing setting" On a string it accepts "" unless you set AllowEmptyStrings = false. On an int it's meaningless — use [Range]. 7.8
"Config changes apply without a restart" Only for IOptionsMonitor/IOptionsSnapshot. IOptions<T>, connection strings, Kestrel endpoints and DI registrations are all fixed at startup. 7.9
"Environment variables reload with the rest" Never. A process reads its environment once at start — an OS behaviour, not a framework one. So most deployments reload nothing. 7.9
"OnChange fires once per edit" Editors write in two steps, so it commonly fires twice. Debounce it, and dispose the subscription or it leaks. 7.9
"A custom provider can inject DbContext" Providers run before DI exists. And a throwing Load() stops the app booting — a config source that's also a runtime dependency is risky. 7.10
"PercentageFilter gives a 10% rollout" It's evaluated per call, so one user gets different answers on refresh. Use TargetingFilter for a real rollout. 7.11
"A misspelled feature flag will error" IsEnabledAsync returns false for an unknown flag, so the feature is silently off forever. Use constants. 7.11

Security

⚠️ The plausible answer ✅ What's actually true Topic
"JWTs are encrypted" A standard JWT is signed, not encrypted. The payload is base64 — anyone can read it. Never put secrets in a JWT. 15.5
"Store the JWT in localStorage" localStorage is readable by any XSS payload. An HttpOnly, Secure, SameSite cookie is safer for browser clients. 15.12
"You can't revoke a JWT, so it's insecure" You can't revoke a stateless token — that's why access tokens are short-lived and revocation happens at the refresh-token layer. 15.7
"APIs don't need CSRF protection" Cookie-authenticated APIs absolutely do. Bearer-token APIs don't, because the browser doesn't attach the token automatically. The distinction is how you authenticate, not whether you're an API. 17.4
"CORS protects my API" CORS is a browser restriction, not a server-side access control. curl ignores it entirely. It is not authorization. 10.10
"EF Core makes SQL injection impossible" Only for LINQ. FromSqlRaw, ExecuteSqlRaw, and dynamic SQL are all still injectable. 17.2
"Auth works locally, so it works in the farm" Data Protection keys are per-machine by default. Two servers means cookies and antiforgery tokens issued by one are rejected by the other. 17.6

Routing

⚠️ The plausible answer ✅ What's actually true Topic
"Routing runs my controller" It only matches. Execution happens at the end of the pipeline — that gap is where authentication and authorization run. 8.1
"I can read the route values in any middleware" GetEndpoint() and RouteValues are empty before UseRouting. Middleware above it sees nothing. 8.1
"I need to call UseRouting myself" WebApplication inserts it automatically. You only add it explicitly to place middleware after the match — and doing so disables auto-insertion. 8.2
"My CORS policy is broken" Often it's ordering: UseCors after UseAuthentication means the unauthenticated OPTIONS preflight is 401'd before CORS can answer. 8.2
"Adding [Route] to one action is harmless" That action becomes invisible to conventional routing — its old URL now 404s. 8.3
"[ApiController] works without a route attribute" It throws at startup. Attribute routing is mandatory, deliberately — deriving public URLs from method names means renaming one changes your API. 8.3
"{id?} and {id=1} are the same" With ? a missing int becomes 0. With =1 you get 1. Prefer defaults for numbers. 8.4
"I can put an optional parameter anywhere" It must be last. Segments match positionally, so anything after an optional is unreachable. 8.4
"page is a fine route parameter name" It's reserved by Razor Pages, along with controller, action, area and handler. Use pageNumber or the query string. 8.4
"I can match on the query string in a template" Templates match the path only. [HttpGet("orders?status={status}")] doesn't work — use [FromQuery]. 8.4
"Route constraints validate input" A failed constraint gives a bare 404, not a 400 with a message. They disambiguate routes; validation belongs in the action. 8.5
":datetime is a safe constraint" It parses using the current culture, so the same URL means different dates on different servers. 8.5
"Link generation throws if it fails" It returns null, silently — constraints run during generation too. Interpolating that into an email gives a missing link and no error. 8.6
"Url.Action uses only the values I pass" It reuses ambient route values from the current request, so an area or version you didn't mention leaks into the URL. LinkGenerator doesn't. 8.6
"The first matching route wins" For attribute routes it's the most specific, compared segment by segment — registration order is irrelevant. For conventional routes it is registration order. Opposite rules. 8.7
"An ambiguous route fails at startup" AmbiguousMatchException is thrown per request. The app starts fine and one URL returns 500. 8.7
"A URL that matches no action returns 404" If the template matches but the HTTP method doesn't, you get 405 Method Not Allowed. 8.7
"asp-area can be omitted to leave the area" Omitting it inherits the current area. You need asp-area="" — an empty string — to clear it. 8.8
"Attribute routing means I can drop [Area]" View discovery still depends on it. Without it Razor looks in Views/ instead of Areas/{Area}/Views/. 8.8
"An endpoint in a group can be made public by adding it after" Group authorization applies to everything in it. Use AllowAnonymous — which wins regardless of order — or better, a sibling group. 8.9
"MapFallbackToFile is safe in an API" A mistyped API URL then returns HTML with a 200, and the client tries to parse a web page. Use {*path:nonfile}. 8.10
"A catch-all route is just a wildcard" It captures ../ too. files/{**path} with Path.Combine serves your appsettings.json. Never build a file path from one. 8.10
"Slug-only URLs are cleaner" They break on every rename, including external links you don't control. Use ID + slug and redirect stale slugs to the canonical URL. 8.10

MVC, Razor Pages and views

⚠️ The plausible answer ✅ What's actually true Topic
"MVC means Model = my EF entity" "Model" means three different things — the domain model, the ViewModel and the model binder's target. Passing an entity to a view is the fat-controller road. 9.1
"Business logic in the controller is fine if it's short" Short logic grows. The controller's job is HTTP: bind, delegate, choose a result. Logic there is untestable without a controller. 9.1
"Controller and ControllerBase are interchangeable" ControllerBase has no View() or ViewBag — it's for APIs. Inheriting Controller in an API drags in view machinery you never use. 9.2
"Only methods with [HttpGet] are actions" Every public method on a controller is an action by default. A public helper becomes a routable endpoint. Mark it [NonAction] or make it private. 9.2
"A controller is a singleton I can cache state in" It's created per request and disposed after. Instance state does not survive, and storing it there is a bug waiting for concurrency. 9.2
"return condition ? Ok(x) : NotFound(); compiles" It doesn't with ActionResult<T> — the ternary can't pick a common type. Use if/else or cast one branch. 9.3
"401 and 403 are both 'access denied'" 401 = we don't know who you are (authenticate). 403 = we know, and you still can't. Unauthorized() on a logged-in user causes a redirect loop. 9.3
"IActionResult and ActionResult<T> are the same" ActionResult<T> declares the success type, so Swagger and the client know the shape without an extra [ProducesResponseType]. 9.3
"Razor output needs manual HTML encoding" @value encodes automatically. It's @Html.Raw that doesn't — and that's where the XSS is. 9.4
"_ViewImports and _ViewStart are the same kind of file" _ViewStart runs code before each view (usually setting Layout). _ViewImports adds directives — @using, @inject, @addTagHelper. Neither replaces the other. 9.4
"Tag helpers work as soon as I install the package" They need @addTagHelper in _ViewImports. Without it asp-for is just an unknown attribute rendered verbatim — silently. 9.4
"Html.Partial is the normal way to render a partial" It's synchronous over async work and can deadlock. Use <partial name="..." /> or await Html.PartialAsync. 9.5
"A partial view can fetch its own data" A partial shares the parent's context and has no logic of its own. If it needs data, you want a View Component. 9.5
"ViewBag and ViewData are different storage" Same dictionary. ViewBag is a dynamic wrapper over ViewData. Set one, read the other. 9.6
"A ViewBag typo is a compile error" It's dynamic — typos compile fine and silently render nothing. That's the whole argument for ViewModels. 9.6
"TempData survives until I clear it" It's read-once. Reading it marks it for deletion — so reading it in a layout means the view finds nothing. Use Peek to read without consuming. 9.6
"TempData needs no configuration" It needs a session or the cookie provider, and cookie TempData is size-limited and visible to the client. Don't put objects or secrets in it. 9.6
"Razor Pages is MVC with the controller removed" It's page-based routing over the same infrastructure: @page turns the file into an endpoint and the PageModel holds the handlers. Filters, DI and model binding are identical. 9.7
"@page is optional at the top of a Razor Page" Without it the file isn't a page at all — it's treated as a view and the route never matches. 9.7
"[BindProperty] binds on GET too" It doesn't, by design. You need [BindProperty(SupportsGet = true)] — and that opens the property to query-string input. 9.7
"Reusing the entity as the form model saves code" It's over-posting: model binding fills every settable property from the request, including IsAdmin. Bind to an input model. 9.8
"Passing an entity to the view is harmless" The view touching an unloaded navigation fires a query while rendering — N+1 in the middle of the response. Project to a ViewModel in the query. 9.8
"Blazor Server scales like a normal web app" It holds a circuit — memory plus a live WebSocket — per connected user, and needs a SignalR backplane to run more than one instance. 9.9
"OnInitializedAsync runs once per page load" With prerendering it runs twice — once server-side, once when interactivity connects. Two API calls, duplicated side effects. 9.9
"Blazor WebAssembly code is safe on the client" The DLLs are downloaded and decompilable. No secrets, and every authorization check must be repeated on the server. 9.9
"Static files are protected by [Authorize] somewhere" UseStaticFiles normally runs before authentication. Anything in wwwroot is public to anyone with the URL. 9.10
"Users will get the new CSS after a deploy" Not if it's cached under the same URL. asp-append-version="true" appends a content hash so the URL changes when the file does. 9.10
"MapFallbackToFile can go anywhere" Before MapControllers it swallows the API routes and returns HTML where the client expected JSON. 9.10
"AllowAnyOrigin() plus AllowCredentials() is a quick fix" It throws — the CORS spec forbids the combination. Name the origins explicitly. 9.10

Web API

⚠️ The plausible answer ✅ What's actually true Topic
"PUT and PATCH are basically the same" PUT replaces the whole resource and is idempotent. PATCH applies a partial change and is not necessarily idempotent. 10.2
"POST is idempotent if I write it carefully" POST is defined as non-idempotent. Making a POST endpoint safe to retry requires an explicit idempotency key. 10.13
"I need to check ModelState.IsValid in every action" With [ApiController], invalid models are auto-rejected with a 400 before your action runs. The manual check is dead code. 10.4
"Return the entity — a DTO is boilerplate" Entities leak your schema, invite over-posting, and cause lazy-loading serialization cycles. The DTO is the boundary. 10.11
"404 means the route was wrong" It also means "resource not found" — and returning 404 vs 403 for an unauthorized resource is a deliberate choice about information disclosure. 10.3
"REST just means JSON over HTTP" It means resources at URLs acted on by standard verbs. POST /api/getOrder is RPC wearing REST's clothes. 10.1
"Our API is fully RESTful" Without hypermedia it's Level 2 on the Richardson model — like nearly every API. Say so; the honesty reads better than the claim. 10.1
"Session state in an API is fine" It breaks statelessness and works perfectly on one server, then fails on scale-out when request two lands elsewhere. 10.1
"Every safe verb is idempotent and vice versa" Only the first half. DELETE is idempotent and definitely not safe. 10.2
"DELETE isn't idempotent — the second call 404s" Idempotency is about server state, not the status code. After one call it's gone; after five it's still gone. 10.2
"PUT updates the fields I send" It replaces the whole resource. Anything absent from the payload is nulled — the classic hand-rolled PUT bug. 10.2
"A GET with a small side effect is harmless" Crawlers, link previews and prefetch will trigger it. GET /users/5/delete has wiped real databases. 10.2
"patch.ApplyTo(dto) throws on a bad patch" It records the failure in ModelState and carries on. Skip the check and an invalid patch returns 204 having done nothing. 10.2
"401 means you're not allowed" 401 is misnamed — it means unauthenticated. 403 means we know who you are and the answer is still no. 10.3
"200 with {success: false} is fine, the body says so" It defeats retries, caching and monitoring. Your dashboards show 100% success while users fail. 10.3
"An empty search result is a 404" It's 200 with []. The collection exists and the query succeeded — it just matched nothing. 10.3
"A duplicate email on signup is a 400" The request was valid; it conflicts with current state. That's 409 — and it tells the client to refetch, not to fix their payload. 10.3
"[ApiController] is optional sugar" It makes attribute routing mandatory — the app throws at startup without a route attribute. 10.4
"A filter object on a GET binds from the query string" It's a complex type, so it infers [FromBody] and binds nothing. [FromQuery] is required. 10.4
"[ApiController] validates my model" It validates annotations on the bound model. Objects you build afterwards — a patched DTO, a mapped entity — are never revalidated. 10.4
"Accept: application/xml gets XML" Only JSON ships by default, and an unsatisfiable Accept silently gets JSON anyway unless ReturnHttpNotAcceptable is set. 10.5
"JSON casing matches my C# properties" Output is camelCase, so a JS client reading response.OrderId gets undefined — silently. 10.5
"Enum values are stable in the JSON" They serialize as numbers, so inserting a member mid-enum renumbers the contract. Add JsonStringEnumConverter. 10.5
"AddNewtonsoftJson() only affects the action that needs it" It changes serialization app-wide — null handling, dates and casing included. 10.5
"Adding a field is always safe" Adding is. Changing a default sort order or page size is breaking in practice, even though the schema never moved. 10.6
"We'll retire v1 when nobody uses it" Without per-version usage logging you can never prove that. Measure first — otherwise the answer is always "leave it running". 10.6
"Deep pagination is just slower" OFFSET 100000 reads 100,020 rows and discards 100,000. Page 1 is instant and page 5000 times out. 10.7
"Offset pagination returns every row eventually" Not on a table being written to. Rows shift between requests, so you silently skip some and see others twice. 10.7
"Sorting by status is fine" Not unless it's a total ordering. Ties order arbitrarily, so rows land on two pages and others vanish. Append the primary key. 10.7
"?pageSize= just controls the page size" Uncapped it's a DoS vector — one request, a full table load and serialization. Clamp it server-side. 10.7
"ProblemDetails is on by default" For status codes returned from actions, yes. Unhandled exceptions and routing 404s are not — you need UseExceptionHandler and UseStatusCodePages. 10.8
"Including the exception message helps debugging" On a 500 it leaks hostnames, file paths and database account names. Return a traceId; log the detail. 10.8
"My IExceptionHandler chain covers everything" If every handler returns false the exception propagates to a bare 500. The last one must be an unconditional catch-all. 10.8
"AddOpenApi() gives me Swagger UI" It generates the document only. /swagger is a 404 in .NET 9 until you add Scalar or Swagger UI yourself. 10.9
"The generated schema documents my API" Only what it can infer. Without [ProducesResponseType] and NRTs enabled, every error is undocumented and every property optional. 10.9
"CORS secures my API" It's enforced by the browser. curl, Postman and other servers ignore it entirely. Authentication secures your API. 10.10
"CORS protects against CSRF" The same-origin policy blocks reading the response, not sending the request. The side effect already happened. 10.10
"CORS works for public endpoints but not authenticated ones" UseCors is after UseAuthorization. Preflights carry no credentials, so they're 401'd before CORS runs. 10.10
"SetIsOriginAllowed(_ => true) is the workaround" It reflects any origin back — functionally "allow everything with credentials", sidestepping the spec's guard. A real vulnerability. 10.10
"My X-Total-Count header works, JS just can't read it" Custom headers are hidden from browsers without Access-Control-Expose-Headers — including Location. 10.10
"A record with init can't be over-posted" Model binding uses init setters happily. Protection comes from the property not existing on the request type. 10.11
"Include then Select is efficient" Projecting makes Include redundant, and it still loads everything first. Drop the Include. 10.11
"AutoMapper is the standard choice" It fails at runtime, not compile time — and since v15 (2025) it needs a commercial licence. Mapperly is source-generated and free. 10.11
"Minimal APIs validate my model like controllers do" There is no automatic validation. Data annotations are simply not checked — add an endpoint filter. 10.12
"Results.Ok() and TypedResults.Ok() are the same" The typed one gives you a testable return type and inferred OpenAPI schema. Use TypedResults. 10.12
"I'll generate a fresh idempotency key on each retry" That defeats the entire mechanism. The key is generated once per logical operation, before the first attempt. 10.13
"Storing the key and the response is enough" Store a request hash too — otherwise a key reused with a different body returns the wrong stored response. 10.13
"If-None-Match protects my PUT" That's the caching header. Concurrency needs If-Match, which returns 412 when someone else saved first. 10.13
"gRPC is just a faster REST" Different model — contract-first, binary, HTTP/2 only, and a browser can't call it without a proxy. 10.14
"GraphQL is strictly better than REST" It kills HTTP caching, is N+1 by construction without DataLoader, is a DoS vector without depth limits, and moves authorization to every field. 10.14
"Renaming a .proto field breaks clients" Names are free to change. Reusing or renumbering a field number is what silently corrupts data. 10.14

Performance

⚠️ The plausible answer ✅ What's actually true Topic
"new HttpClient() per call, wrapped in using" Sockets stay in TIME_WAIT after disposal. Under load this exhausts ports. Use IHttpClientFactory. 19.10
"A static HttpClient fixes it" It fixes socket exhaustion but never picks up DNS changes. IHttpClientFactory handles both via handler rotation. 19.10
"IMemoryCache works fine when we scale out" Each instance has its own cache. Users get inconsistent reads depending on which server they hit. 19.3
"Adding a cache made it faster, done" Without stampede protection, a cache miss on a hot key sends every concurrent request to the database at once. 19.4

C

⚠️ The plausible answer ✅ What's actually true Topic
"throw ex; and throw; are the same" throw ex; resets the stack trace, destroying the original throw site. Use bare throw;. 1.20
"Structs are always faster than classes" Large structs are expensive to copy, and boxing them undoes the benefit entirely. The guidance is small, immutable, and short-lived. 1.2
"Nullable reference types stop null reference exceptions" They're compile-time hints only. Nothing is enforced at runtime, and data crossing a serialization boundary ignores them completely. 1.15
"Value types always live on the stack" Only as locals. As class fields, captured lambda variables, or async locals they live on the heap. 1.1
"Passing a class means pass by reference" It passes a reference, but by value. Reassigning the parameter does not change the caller's variable. 1.1
"record means immutable" It means value equality plus with. Immutability comes from init, which the positional form happens to generate. 1.2
"name.Trim(); trims the string" Strings are immutable. Every method returns a new string — you must assign the result. 1.3
"StringBuilder is always faster than +" For a fixed handful of joins the compiler emits one String.Concat, which beats a StringBuilder. Use it for loops and unknown counts. 1.3
"protected internal is the restrictive one" Backwards. protected internal = assembly OR derived (wider). private protected = derived AND same assembly (narrower). 1.4
"Changing a const in a library updates consumers" const values are inlined into the consuming assembly. They keep the old value until recompiled. Use static readonly. 1.6
"readonly makes the object immutable" It only stops the field being reassigned. A readonly List<T> can still be added to. 1.6
"new and override do the same thing" override dispatches on the runtime object; new dispatches on the declared variable type. Same object, two answers. 1.7
"You can call a virtual method from a constructor" Base constructors run first, so the derived override runs before the derived fields are initialised. Null reference exceptions that look impossible. 1.7
"A for loop lambda captures the value" It captures the variable, and a for loop has only one. All lambdas see the final value. foreach is safe since C# 5; for is not. 1.13
"An extension method with the same name overrides the real one" The real instance method always wins, silently. No warning that your extension was ignored. 1.14
"a?.B.C protects the whole chain" Only a. If B is null you still get a NullReferenceException. Every link needs its own ?.. 1.16
"?? handles empty strings" It only checks null. "", 0 and false all pass through as real values. 1.16
"var and dynamic are similar" var is compile-time inference with full type safety and zero runtime cost. dynamic disables type checking entirely. Nothing alike. 1.22
"A finalizer is how you clean up" A finalizer makes the object survive an extra GC cycle and runs at an unpredictable time. It's a last-resort safety net. Use IDisposable. 1.21
"A class primary constructor parameter is a property" In a record it is. In a class it's a private, mutable captured field — not exposed, not readonly. 1.26
"Single() and First() differ only in style" Single() throws if there's more than one match — and to know that, it must scan further. Different semantics and different cost. 2.9
"Enumerating an IEnumerable twice is free" For a deferred query it executes twice. Against a database, that's two round trips. 2.6

Collections and LINQ

⚠️ The plausible answer ✅ What's actually true Topic
"Returning IEnumerable<T> from a repository is good practice" It silently kills SQL translation. Every later Where runs in memory over the whole table. Return IReadOnlyList<T> after materialising. 2.1
".Count() and .Count are the same" .Count() on an IEnumerable walks the entire sequence. .Count on an ICollection is an instant property. 2.1
"list.Contains(x) is fine inside a loop" That's O(n×m). Two lists of 10,000 = 100 million comparisons. Convert to a HashSet first — one character, ~10,000× faster. 2.2
"Dictionary iteration order is stable" No order is guaranteed, ever. It looks stable in testing and changes when the internal array resizes. 2.2
"A ConcurrentDictionary makes my code thread-safe" Each operation is safe; a sequence of them is not. if (!d.ContainsKey(k)) d[k]=v still races. Use GetOrAdd. 2.3
"GetOrAdd's factory runs once" Only the store is atomic. The factory can run on several threads at once. Wrap in Lazy<T> if it's expensive or has side effects. 2.3
"Argument validation in an iterator method throws when called" The whole body is deferred, including the validation. It throws at the foreach, far from the cause. Split into an outer method + local iterator. 2.4
"A second OrderBy adds a secondary sort" It discards the first sort entirely. Use ThenBy. 2.5
"Count() > 0 and Any() are equivalent" Any() stops at the first match; Count() walks everything. Against a DB that's EXISTS vs COUNT(*). 2.5
"A LINQ query runs when you write it" It's a recipe, not a meal. It runs on enumeration — and runs again every time you enumerate. 2.6
"Func<T,bool> and Expression<Func<T,bool>> are interchangeable" Func is compiled code you can only run. Expression is data describing code, which is the only reason EF Core can emit SQL. 2.7
"'Could not be translated' is EF Core being unhelpful" It's the good outcome. The old behaviour was silent client evaluation — downloading the whole table. 2.7
"Sum, Max and Average behave the same on an empty sequence" Sum returns 0. Max, Min and Average throw. 2.8
"FirstOrDefault returns null when nothing matches" For a value type it returns 0 / false. You cannot tell "missing" from "legitimately zero". 2.9

Async and threading (section 2)

⚠️ The plausible answer ✅ What's actually true Topic
"A Task runs on a separate thread" Not for I/O. During an async network call no thread exists for that operation — the hardware does the work. 2.10
"Task.Run makes I/O faster" It blocks a pool thread on something designed not to need one. Just await the async method. 2.10
"await pauses the method" It returns to the caller and registers a callback. Nothing is paused; the thread is released. 2.11
"Three awaits in a row run concurrently" They're strictly sequential. Capture the tasks first, then await Task.WhenAll — 600 ms becomes 200 ms. 2.12
"Task.WhenAll gives you all the exceptions" Awaiting rethrows only the first. The rest are on task.Exception.InnerExceptions. 2.12
"ValueTask is a faster Task, use it everywhere" Await it once only, never block on it, never pass it to WhenAll. It's a library-author optimisation. 2.12
".Result is safe in ASP.NET Core since there's no deadlock" True about deadlock, but it blocks a pool thread → thread-pool starvation. Signature: huge latency with idle CPU. 2.13
"Add ConfigureAwait(false) everywhere" In ASP.NET Core app code it does nothing — there's no context. It matters in libraries. 2.13
"Accepting a CancellationToken makes a method cancellable" Only if you pass it down and check it. An ignored token is worse than none — it advertises a capability that doesn't exist. 2.14
"OperationCanceledException should be logged as an error" It's routine traffic — a user closed a tab. Logging it as an error buries real failures. 2.14
"A try/catch around an async void call catches its exceptions" It catches nothing — the method already returned. The exception crashes the process. 2.15
"list.ForEach(async x => await F(x)) awaits each item" ForEach takes an Action, so every lambda is async void. Use foreach or Task.WhenAll. 2.15
"catch (SqlException) works the same either way" With await, yes. With .Result, the exception is wrapped in AggregateException and the typed catch is dead code. 2.16
"[EnumeratorCancellation] is optional boilerplate" Without it, WithCancellation is silently ignored and your async stream cannot be cancelled. 2.17
"count++ is one operation" It's read, add, write. Two threads interleave and an increment is lost. Use Interlocked.Increment. 2.18
"volatile makes a field thread-safe" It only stops caching and reordering. It does not make operations atomic — volatile count++ still races. 2.18
"Parallel.ForEach speeds up my API endpoint" The server is already parallel. It steals threads from other requests, so one request gets faster and total throughput drops. 2.19
"Adding to a List<T> inside Parallel.ForEach is fine" List<T> is not thread-safe — you get lost items, corruption, or IndexOutOfRangeException. Use a concurrent collection. 2.19

Add your own

The traps you personally get wrong are worth ten of the ones above. Every time you fumble something in a mock or a real interview, add a row here the same day.

⚠️ What I said ✅ What's actually true Date