ASP.NET Core
Microsoft's cross-platform .NET web framework: Kestrel hosting, the middleware pipeline, Minimal APIs and MVC, DI, configuration, auth and caching. It anchors most .NET backend interviews.
on this pageshowhide
guide
overview
~2 minASP.NET Core is Microsoft's open-source, cross-platform framework for HTTP APIs and server-rendered web apps on .NET. A request reaches a server, usually Kestrel, travels through an ordered chain of middleware, is matched to an endpoint, and arrives at a handler whose parameters are bound from the request and whose dependencies come from the built-in container. Interviewers build .NET backend rounds on it because so many production bugs in the stack have a precise home in one of those steps: a middleware in the wrong place, a service with the wrong lifetime, a setting overridden by a source loaded later. The hub follows that path. [Project setup and startup](/topics/be-aspnet-core-foundations) and [servers and hosting](/topics/be-aspnet-core-hosting) cover how the process starts and how traffic reaches it. [HTTP pipeline composition](/topics/be-aspnet-core-middleware), the [endpoint routing engine](/topics/be-aspnet-core-routing), [service registration](/topics/be-aspnet-core-di) and [configuration and options](/topics/be-aspnet-core-config) are the core every other section assumes. Handlers come in two styles, [Minimal APIs](/topics/be-aspnet-core-minimal-apis) and [MVC and Razor Pages](/topics/be-aspnet-core-mvc), both fed by the [model binding pipeline](/topics/be-aspnet-core-modelbinding) and both reporting failure through [errors and Problem Details](/topics/be-aspnet-core-errors). Around them sit [sign-in and permissions](/topics/be-aspnet-core-auth), [built-in security defenses](/topics/be-aspnet-core-security), [request and session state](/topics/be-aspnet-core-state), [database plumbing](/topics/be-aspnet-core-data), the [caching stack](/topics/be-aspnet-core-caching), [calls to downstream APIs](/topics/be-aspnet-core-http-clients), [raw push channels](/topics/be-aspnet-core-realtime), [off-request processing](/topics/be-aspnet-core-background) and [cultures and translations](/topics/be-aspnet-core-localization). The production end covers [observability](/topics/be-aspnet-core-logging), [API contracts and protocols](/topics/be-aspnet-core-apis), [testing](/topics/be-aspnet-core-testing), [performance and deployment](/topics/be-aspnet-core-performance) and [solution layout](/topics/be-aspnet-core-architecture). Junior rounds stay on mechanics: what `Program.cs` does, where a parameter's value comes from, what a lifetime means. Senior rounds turn into diagnosis and trade-offs: why a valid token earned a 401, why a singleton serves stale data, which cache layer fits which data, how to change an API without breaking its callers. At every level, naming the version an answer depends on counts in your favour. Learn startup, the pipeline and the container first; configuration, binding and sign-in follow from them. Caching, security, background work and the rest are much easier once you can say exactly where in the request each one runs.
primer
### Two phases: build, then run `Program.cs` has two halves with a hard line between them. Before `builder.Build()` you register services and shape configuration; after it the container is fixed, and you compose the pipeline and map endpoints. Many startup questions, such as why a registration seems to do nothing or what `app.Run()` waits for, come down to which side of that line the code sits on. ### The pipeline is an ordered chain Every request passes through middleware in the order they were added. Each one can act before and after the rest, or end the request on its own. Order is behaviour: exception handling has to wrap what it is meant to catch, authentication has to come before authorization, and anything that needs the selected endpoint has to come after routing. When an interviewer shows you a `Program.cs` and asks what is wrong, the answer is usually a line in the wrong place. ### Endpoints carry their own rules Endpoint routing separates choosing an endpoint from running it. An endpoint is a delegate plus **metadata**: its route, HTTP methods, authorization requirements, CORS, rate-limit and cache policies, OpenAPI description. Middleware placed between matching and execution reads that metadata to decide what to do. That is why `[Authorize]` on a controller and `RequireAuthorization()` on a Minimal API end up enforced by the same authorization middleware. ### Lifetimes decide sharing The built-in container creates services as **singleton**, **scoped** or **transient**. The lifetime decides who shares an instance and when it is disposed, and a mismatch is the classic bug: a long-lived service holding a shorter-lived one keeps it far longer than intended. Senior questions extend this to anything with state: a `DbContext`, the handlers behind `HttpClient`, options objects, and background loops that have no request scope of their own. ### Configuration is layered, then typed Settings come from an ordered list of sources (JSON files, environment-specific files, user secrets, environment variables, command-line arguments), merged into one key space in which a source added later overrides an earlier one. The **options pattern** then binds sections to classes, and the interface you inject decides whether a running app sees a changed value. Be ready for two questions: which value wins, and why an edit did not take effect. ### Two handler styles, one platform Minimal APIs and MVC controllers sit on the same routing, binding, DI and auth. They differ in how much is convention and where cross-cutting logic lives: route groups and endpoint filters on one side, the MVC filter pipeline and `[ApiController]` on the other. Interviewers ask you to choose one for a new service and defend the choice, and to know what each style does for you implicitly. ### Binding turns text into types Route values, query strings, headers, forms and bodies become typed parameters, by inference or by explicit source attributes, and are validated afterwards. Most "why is this value null" and "why did I get a 415" questions are binding questions: the framework looked in a different place than you expected, or the body was not in a format it could read. ### Async is a capacity decision Requests run on the shared .NET thread pool. Code that blocks a thread while it waits for I/O shrinks how many requests the server can handle at once, and under load that shows up as latency across the whole app rather than in one slow endpoint. Performance conversations start here, before caching, AOT or bigger machines.
- Kestrel
- The cross-platform HTTP server built into ASP.NET Core. It runs inside the app's process and serves traffic directly or behind IIS, Nginx or a cloud load balancer.
- WebApplicationBuilder
- The object WebApplication.CreateBuilder returns. It gathers configuration, logging, host settings and service registrations until Build produces the WebApplication you add middleware and endpoints to.
- Middleware
- A component in the request pipeline that receives the HttpContext and the next component, and can act before and after it or end the request itself.
- RequestDelegate
- The signature at the heart of the pipeline: a function from HttpContext to Task. Middleware chains and endpoints are both built out of it.
- Endpoint
- A request handler together with its metadata, such as route pattern, HTTP methods, authorization, CORS and cache policies. Routing selects it; the end of the pipeline executes it.
- Route template
- A URL pattern such as /orders/{id:int} with literal segments, parameters, optional and default values, and constraints. Routing uses it to match requests and to generate links.
- Service lifetime
- How long the DI container keeps an instance: singleton for the whole app, scoped for one scope (normally one request), transient for every resolution.
- Captive dependency
- A shorter-lived service held by a longer-lived one, such as a scoped DbContext inside a singleton, so it outlives its intended scope and may be shared across requests.
- Options pattern
- Binding a configuration section to a typed class and injecting it through IOptions, IOptionsSnapshot or IOptionsMonitor, which differ in when they see changed values.
- Model binding
- The step that fills handler or action parameters from route values, the query string, headers, form fields and the body, before validation runs.
- ProblemDetails
- The standard JSON error body defined by RFC 9457, with type, title, status and detail fields. ASP.NET Core can write it for exceptions and bare error status codes.
- Authentication scheme
- A named handler, such as cookies or JWT bearer, that reads a request's credentials into HttpContext.User and defines how to challenge or forbid a caller.
- Authorization policy
- A named set of requirements a user must satisfy, evaluated against HttpContext.User for every endpoint that requires it. Role and claim checks are expressed as policies too.
- Hosted service
- A long-running task the host starts with the app and stops at shutdown, usually written by deriving from BackgroundService and registered with AddHostedService.
- IHttpClientFactory
- The factory that hands out HttpClient instances over pooled, periodically recycled message handlers, with named or typed configuration and optional resilience handlers.
- Data Protection
- ASP.NET Core's key-ring API for encrypting and signing payloads such as authentication cookies and antiforgery tokens. Instances serving the same users must share the key ring.
- WebApplicationFactory
- A test fixture that boots the app's real Program.cs on an in-memory server and returns an HttpClient, so integration tests run the whole pipeline without a socket.
- Native AOT
- Publishing the app as ahead-of-time compiled native code for fast startup and low memory, at the cost of features that depend on runtime reflection or code generation.
Trace one request from socket to response. Kestrel, alone or behind IIS or a reverse proxy, accepts the connection and builds an `HttpContext`. When a proxy terminated TLS, forwarded-headers middleware restores the client's address and scheme. The exception handler wraps everything after it; HTTPS redirection, static files and CORS can answer or reject the request early. Routing selects an endpoint and exposes its metadata, authentication sets `HttpContext.User`, and authorization checks the endpoint's requirements against that user. Only then does the handler run, a Minimal API delegate or a controller action wrapped in MVC filters, with parameters bound from the request and services resolved from the request's scope. Its result becomes the response; with the setup below, an exception on the way out becomes Problem Details; and the scope disposes what it created. The startup that makes that path possible fits in about a dozen lines, and most of the hub hangs off one of them: ```csharp var builder = WebApplication.CreateBuilder(args); // config, logging, Kestrel, DI builder.Services.AddScoped<IOrderReader, SqlOrderReader>(); builder.Services.AddProblemDetails(); builder.Services.AddAuthentication().AddJwtBearer(); builder.Services.AddAuthorization(); var app = builder.Build(); // registrations are frozen here app.UseExceptionHandler(); // outermost: sees later failures app.UseAuthentication(); app.UseAuthorization(); app.MapGet("/orders/{id:int}", async Task<Results<Ok<OrderView>, NotFound>> (int id, IOrderReader orders) => await orders.FindAsync(id) is { } view ? TypedResults.Ok(view) : TypedResults.NotFound()) .RequireAuthorization(); app.Run(); ``` The registrations belong to [service wiring](/topics/be-aspnet-core-di) and [configuration](/topics/be-aspnet-core-config), the `Use` calls to [pipeline composition](/topics/be-aspnet-core-middleware) and [sign-in](/topics/be-aspnet-core-auth), the `{id:int}` template to [routing](/topics/be-aspnet-core-routing), and the typed result to [Minimal APIs](/topics/be-aspnet-core-minimal-apis). Swapping the two `UseAuth` lines, or moving the exception handler below them, changes behaviour without any compile error, which is exactly what makes these lines good interview material. The remaining sections attach to the same path rather than sitting beside it: - **Caching** works at two levels: data caches are services a handler calls, while output caching is middleware that can answer before the handler runs at all. - **Security defenses** such as CORS, antiforgery, HSTS and rate limiting are middleware or filters, several of them configured per endpoint through metadata. Data Protection keys sign the cookies that authentication and antiforgery rely on. - **Background work and push channels** break the request-response rhythm: hosted services have no request scope, and a WebSocket or SSE endpoint keeps its request open for the life of the connection. - **Observability** reads the path at each step: categorised logs, request logs from middleware, traces that follow outgoing `HttpClient` calls, and health checks served as ordinary endpoints. - **Testing** boots this same `Program.cs` on an in-memory server, so integration tests exercise the real middleware order.
- Project Setup & Startup →
Program.cs, WebApplicationBuilder and environments: the startup every other section takes for granted, and where many interviews open.
- HTTP Pipeline Composition →
How the request pipeline is composed and why order matters; the source of most misconfiguration questions.
- IServiceCollection Wiring →
Registration and lifetimes, so you can say who shares an instance and spot a captive dependency.
- Configuration Sources & Options →
Which configuration source wins and which options interface to inject; needed before hosting, auth or caching settings make sense.
- Model Binding Pipeline →
How request data becomes typed parameters and how bad input turns into a 400, under both handler styles.
- Sign-In & Permissions →
Schemes, tokens and policies; it builds on the pipeline order and endpoint metadata covered in the earlier steps.
Putting
UseAuthorizationbeforeUseAuthentication, or the exception handler after the middleware it should catch: the app compiles and starts, and the bug surfaces only as wrong status codes.Holding a scoped service such as a
DbContextin a singleton and trusting startup to complain; scope validation runs by default in Development, not in Production. See Lifetimes & Captive Dependencies.Using route constraints to validate input: a failing constraint removes the endpoint from matching, so the caller gets a 404 instead of an error explaining the bad value.
Blocking on
.Resultor.Wait()in request code; it passes every test at low traffic and starves the thread pool under real load.Creating a new
HttpClientfor each outgoing call; under load it can exhaust sockets. Register clients withAddHttpClientand let the factory manage handlers.Assuming a server runs in Development because your machine did: with no environment set the app runs as Production, and launchSettings.json is never deployed.
Returning EF Core entities straight from endpoints, which exposes every public property and ties the JSON contract to the table schema.
Treating CORS as access control: it tells browsers which origins may read responses and stops no other client.
Scaling out without a shared Data Protection key ring, so cookies and antiforgery tokens issued by one instance can be rejected by the next.
This guide assumes ASP.NET Core 10 on .NET 10, a long-term-support release. Plenty of production apps run older versions, and several questions turn on what changed along the way: - **1.x and 2.x** were a rewrite separate from System.Web-based ASP.NET; 2.x could still run on .NET Framework. - **3.0** moved hosting onto the Generic Host, made endpoint routing the default and dropped .NET Framework support. - **6** introduced the minimal hosting model, one `Program.cs` built on `WebApplicationBuilder` instead of a `Startup` class, together with Minimal APIs. - **7** added route groups, endpoint filters, `TypedResults`, the rate limiting middleware and output caching. - **8** added `IExceptionHandler`, keyed services and Native AOT support for Minimal API apps. - **9** shipped built-in OpenAPI document generation, and the API template stopped including Swashbuckle. - **10** added built-in validation for Minimal APIs and Server-Sent Events results. Since .NET 5, even-numbered releases are long-term support; odd-numbered ones have a shorter window, which is why teams often move from one even release to the next. When an answer depends on version (template shape, defaults, whether an API exists at all), say which one you are describing. Interviewers maintaining an older app will ask about the `Startup` era, and naming it is part of a good answer.
ASP.NET Core is the default web stack in .NET, so interviewers usually place it against other ecosystems rather than against rivals inside its own: Spring Boot on the JVM, Express or NestJS on Node.js, Django or FastAPI in Python, Go's standard library with a router. The comparison that holds up is about the platform as a whole, a statically typed compiled runtime that ships its own server, DI container, configuration and auth stack, rather than about benchmark numbers. Its predecessor, ASP.NET on .NET Framework (Web Forms, MVC 5, Web API 2), is Windows-only and still turns up in migration questions. Within .NET it is the base other pieces run on: SignalR for real-time messaging, Blazor for interactive UI, gRPC services and the YARP reverse proxy all sit on top of it. Around it are the companions you will be asked to justify: EF Core or Dapper for data, Serilog or OpenTelemetry for telemetry, FluentValidation, MediatR-style request handlers, mapping libraries, Polly-based resilience, and Aspire for local orchestration. A strong candidate knows which of these ship with the framework and which are third-party choices with a cost. [Raw Push Channels](/topics/be-aspnet-core-realtime) covers when a bare WebSocket or SSE stream beats SignalR.
explore
- Project Setup & Startup21 questions
- Starter Templates & SDK5 questions
- WebApplicationBuilder & Program.cs5 questions
- Environments & Launch Profiles5 questions
- LTS Support & Version Upgrades6 questions
- Servers & Hosting19 questions
- Kestrel Endpoints & Limits5 questions
- IIS & HTTP.sys5 questions
- Proxies & Forwarded Headers5 questions
- Lifetime Events & Shutdown4 questions
- HTTP Pipeline Composition20 questions
- Middleware Order & Branching5 questions
- Middleware Classes & IMiddleware4 questions
- Static Files & Assets5 questions
- Compression & Timeout Middleware6 questions
- Endpoint Routing Engine16 questions
- Route Templates & Constraints5 questions
- Match Order & Metadata6 questions
- LinkGenerator & URL Helpers5 questions
- Minimal APIs18 questions
- Handler Parameter Inference5 questions
- TypedResults & IResult4 questions
- Route Groups & Filters5 questions
- Automatic Parameter Checks4 questions
- MVC & Razor Pages28 questions
- Controller Conventions5 questions
- Action & Result Filters5 questions
- Views & Layouts6 questions
- Tag Helpers & View Components6 questions
- PageModel Handlers6 questions
- Razor6 questions
- Model Binding Pipeline25 questions
- Parameter Sources & Binders5 questions
- DataAnnotations & ModelState5 questions
- IValidator Injection & Filters4 questions
- JSON Options & Formatters6 questions
- File Uploads & Streaming5 questions
- Configuration Sources & Options16 questions
- Provider Order & Overrides6 questions
- Typed Settings & Validation5 questions
- User Secrets & Key Vault5 questions
- IServiceCollection Wiring14 questions
- Lifetimes & Captive Dependencies5 questions
- Keyed & Open Generic Types5 questions
- Scanning & Third-Party Containers4 questions
- Errors & Problem Details10 questions
- IExceptionHandler & Status Pages5 questions
- ProblemDetails Responses5 questions
- Request & Session State10 questions
- HttpContext Items & Features5 questions
- ISession & TempData5 questions
- Sign-In & Permissions29 questions
- Schemes & Cookie Handler6 questions
- JWT Bearer Tokens6 questions
- Identity Stores & Managers6 questions
- Policies & Requirements5 questions
- OpenID Connect Handler6 questions
- Built-In Security Defenses25 questions
- CORS Policies5 questions
- Antiforgery Tokens5 questions
- HTTPS & HSTS5 questions
- Rate Limiter Middleware5 questions
- Data Protection Keys5 questions
- Database Plumbing10 questions
- DbContext per Request5 questions
- ADO.NET & DbDataSource5 questions
- Caching Stack26 questions
- IMemoryCache Entries5 questions
- Distributed Cache Stores5 questions
- HybridCache Library5 questions
- Output Cache Policies6 questions
- Response Cache Middleware5 questions
- Observability Signals22 questions
- ILogger Categories & Scopes5 questions
- HTTP & W3C Request Logs5 questions
- OpenTelemetry Traces & Metrics6 questions
- Health Check Endpoints6 questions
- API Contracts & Protocols27 questions
- OpenAPI Documents6 questions
- Asp.Versioning Library6 questions
- Hosting gRPC Services6 questions
- OData Endpoints4 questions
- DTO Mapping5 questions
- Calling Downstream APIs11 questions
- Named & Typed Clients5 questions
- Resilience Handlers6 questions
- Raw Push Channels11 questions
- WebSockets Without SignalR6 questions
- SSE Result Streams5 questions
- Off-Request Processing11 questions
- BackgroundService Loops6 questions
- Channel-Based Queues5 questions
- Cultures & Translations10 questions
- String Localizers & Resources5 questions
- Request Locale Providers5 questions
- App Testing Practice21 questions
- WebApplicationFactory Tests5 questions
- Unit Tests & Fakes6 questions
- Real-Database Tests5 questions
- Generated Data & Assertions5 questions
- Performance & Deployment14 questions
- Native AOT & Trimming5 questions
- Throughput & Thread Pool5 questions
- Publishing & Containers4 questions
- Solution Layout & Layers11 questions
- Clean & Vertical Slices5 questions
- Per-Module Registration6 questions
questions
431 · 25 sectionsIn ASP.NET Core 10, which environment does an app run in when nothing sets one, and where does Development come from locally?
basics
~20 sAn ASP.NET Core 10 app runs as Production unless something supplies an environment name. Locally, Development comes from the launch profiles in Properties/launchSettings.json, which dotnet run and the IDEs apply but which are never deployed.
In an ASP.NET Core 10 Program.cs, what do WebApplication.CreateBuilder(args), builder.Build() and app.Run() each do?
basics
~20 sCreateBuilder makes a WebApplicationBuilder with default configuration, logging, Kestrel and DI; Build turns the registered services into a provider and returns a WebApplication for the pipeline and endpoints; Run starts the server and blocks until shutdown.
For ASP.NET Core on .NET, what is the difference between an LTS and an STS release, and how long is each supported?
basics
~20 sASP.NET Core ships with each yearly .NET release, and releases alternate between Long Term Support (at least three years) and Standard Term Support (24 months). .NET 10 is LTS until November 2028; .NET 8 and .NET 9 both end in November 2026.
With the .NET 10 SDK, what does dotnet new webapi generate by default, and how do --use-controllers, --no-openapi and --no-https change it?
basics
~20 sIn .NET 10, dotnet new webapi writes a Minimal API project on Microsoft.NET.Sdk.Web: one weather-forecast MapGet, the built-in OpenAPI document mapped in Development, and HTTPS redirection. --use-controllers, --no-openapi and --no-https switch those parts off or over.
How do you upgrade an ASP.NET Core 8 web app to .NET 10, and what has to change besides the TargetFramework?
basics
~20 sInstall the .NET 10 SDK, set TargetFramework to net10.0, move every Microsoft.AspNetCore., Microsoft.EntityFrameworkCore. and Microsoft.Extensions.* package to 10.0.x, update third-party packages, then fix the new warnings and test against the 9 and 10 breaking changes.
When an ASP.NET Core 10 app is published for IIS, what does the generated web.config tell IIS, and which component acts on it?
basics
~20 sIt registers the ASP.NET Core Module (AspNetCoreModuleV2) as the handler for every request and, in its aspNetCore element, tells that module how to start the app: processPath and arguments, the hosting model (inprocess by default) and stdout logging.
In ASP.NET Core 10, which address does Kestrel listen on when nothing configures a URL, and how do you make it accept connections from other machines?
basics
~10 sWith no URL, port or endpoint configured, Kestrel binds http://localhost:5000: plain HTTP on the IPv4 and IPv6 loopback addresses only. To accept other machines, bind every interface, for example ASPNETCORE_URLS=http://+:5000, HTTP_PORTS=5000 or ListenAnyIP(5000).
Behind a TLS-terminating load balancer, why does an ASP.NET Core app log the balancer's IP and build http:// links, and what does UseForwardedHeaders change?
basics
~20 sKestrel only sees the balancer's plain-HTTP connection, so RemoteIpAddress is the balancer and Scheme is http. UseForwardedHeaders, told to process X-Forwarded-For and X-Forwarded-Proto from a trusted proxy, writes the client's IP and https scheme back onto HttpContext.
When a container sends SIGTERM to an ASP.NET Core 10 API mid-traffic, what is the shutdown sequence, and what do in-flight requests experience?
basics
~10 sSIGTERM triggers StopApplication: ApplicationStopping fires, Kestrel stops accepting connections and lets in-flight requests finish, for up to HostOptions.ShutdownTimeout (30 seconds). Requests still running then have their connections aborted; hosted services stop and ApplicationStopped fires.
In ASP.NET Core, how do you run code when the app starts and when it shuts down, and how can code request a graceful stop?
basics
~10 sUse IHostApplicationLifetime (app.Lifetime in Program.cs): register callbacks on its ApplicationStarted, ApplicationStopping and ApplicationStopped cancellation tokens. Calling StopApplication() triggers ApplicationStopping and the same graceful shutdown that Ctrl+C or SIGTERM starts.
In ASP.NET Core 10, how do you turn on response compression for a JSON API, and why might a JSON response still come back uncompressed?
basics
~20 sCall builder.Services.AddResponseCompression() and app.UseResponseCompression() ahead of whatever writes the response. A JSON response still goes out uncompressed when the client sent no Accept-Encoding, the request is HTTPS (EnableForHttps defaults to false), or its content type isn't listed.
In ASP.NET Core, what shape must a convention-based middleware class have, and how do you add it to the request pipeline?
basics
~10 sA public constructor taking RequestDelegate next and a public Invoke or InvokeAsync method that returns Task and takes HttpContext first. Add it with app.UseMiddleware<T>(), usually wrapped in an IApplicationBuilder extension such as UseBrandResolution().
In ASP.NET Core, what is a RequestDelegate, and how do app.Use and app.Run differ when you build the request pipeline?
basics
~10 sRequestDelegate is the Task-returning delegate that handles one HttpContext. app.Use adds middleware that receives the next delegate and may call it; app.Run adds terminal middleware with no next, so nothing registered after it runs.
In ASP.NET Core, how does app.UseStaticFiles() decide which file to serve for a request, and when does it pass the request on instead?
basics
~20 sUseStaticFiles maps the URL path onto the web root (wwwroot by default). For a GET or HEAD whose extension has a known content type, it streams the matching file and ends the request; anything else goes to the next middleware.
In ASP.NET Core, why does injecting a scoped DbContext into a convention-based middleware's constructor go wrong, and where should it go instead?
basics
~20 sConvention middleware is built once from the root provider. In Development scope validation throws when the pipeline is built; elsewhere one DbContext is captured and shared by every request. Take the DbContext as an InvokeAsync parameter, or use IMiddleware.
In an ASP.NET Core route template, how do a required {slug}, an optional {edition?} and a default-valued {page=1} parameter differ in what they match?
basics
~20 sA required parameter such as {slug} must be present in the URL. An optional {edition?} may be missing and then produces no route value, while a default {page=1} may also be missing but always produces a value.
In an ASP.NET Core controller, how do CreatedAtAction and CreatedAtRoute build the Location header, and why can they throw "No route matches the supplied values"?
basics
~20 sBoth return 201 Created and generate an absolute Location URL through IUrlHelper: CreatedAtAction from an action name and route values, CreatedAtRoute from a route name. If no endpoint fits those values, they throw InvalidOperationException "No route matches the supplied values."
In ASP.NET Core, what do UseRouting and UseEndpoints each do, and why does middleware placed before UseRouting get null from HttpContext.GetEndpoint()?
basics
~10 sUseRouting matches the request and stores the chosen endpoint on HttpContext; UseEndpoints runs that endpoint's delegate. Middleware before UseRouting runs before any endpoint has been selected, so GetEndpoint() returns null there.
In ASP.NET Core, why does an endpoint mapped to /books/{id:int} answer 404 rather than 400 for /books/abc, and what are route constraints really for?
basics
~20 sAn inline constraint like :int is checked while routing matches the URL, so a failing value removes the endpoint from the candidates; with nothing selected the request ends as 404. Constraints exist to tell similar routes apart, not to validate input.
In ASP.NET Core MVC and Razor Pages, when do you use Url.Action, Url.RouteUrl or Url.Page, and what do they return when no route matches?
basics
~20 sUrl.Action targets a controller action by name, Url.RouteUrl a named route, and Url.Page a Razor Page by its path name. All return a path such as /bikes/7, an absolute URL when you pass a protocol, and null when nothing matches.
In ASP.NET Core Minimal APIs, what does app.MapGroup("/api/v1/fleet") return, and how does it apply conventions once to many endpoints?
basics
~20 sIt returns a RouteGroupBuilder, both a route builder and a convention builder: endpoints mapped on it get the group prefix in front of their pattern, and WithTags or AddEndpointFilter on it reach every endpoint inside, nested groups included.
In an ASP.NET Core Minimal API, how does a MapGet or MapPost handler decide where each of its parameters is bound from?
basics
~20 sMinimal APIs infer each parameter's source: a simple type binds from the route if its name is a route parameter, else from the query; registered services come from DI; an unregistered complex type on MapPost is the JSON body.
In an ASP.NET Core Minimal API, what response does a handler produce when it returns a string, a plain object, or an IResult like TypedResults.Ok?
basics
~10 sA string is written as 200 text/plain, any other object is serialized to 200 application/json, and an IResult writes its own status, headers and body through ExecuteAsync; void or Task gives an empty 200.
In ASP.NET Core 10 Minimal APIs, what does builder.Services.AddValidation() do, and what happened to DataAnnotations on handler parameters before it?
basics
~20 sAddValidation switches on built-in validation in .NET 10: a framework endpoint filter checks DataAnnotations and IValidatableObject on bound parameters and body types, nested members included, and answers 400 before the handler runs. Earlier Minimal APIs ignored those attributes.
In an ASP.NET Core Minimal API, how do you write an IEndpointFilter that reads a handler argument and stops the request before the handler runs?
basics
~10 sImplement IEndpointFilter.InvokeAsync(EndpointFilterInvocationContext, EndpointFilterDelegate), read the bound value with context.GetArgument<T>(index), and return a result such as TypedResults.NotFound() without calling next to stop; otherwise return await next(context).
In ASP.NET Core, when should a controller derive from ControllerBase instead of Controller, and which of AddControllers, AddControllersWithViews or AddMvc does it need?
basics
~10 sA JSON API controller derives from ControllerBase, which carries the HTTP result helpers, and needs only AddControllers. Derive from Controller when actions render Razor views, and register AddControllersWithViews; AddMvc also adds Razor Pages.
In ASP.NET Core Razor Pages, how do the @page directive, the Pages folder and OnGet or OnPost methods route a request to code?
basics
~20 sA .cshtml file under Pages starting with @page is an endpoint whose URL is its path, with Index also answering the folder URL; a template after @page appends segments. The PageModel method named On plus the HTTP verb, such as OnPostAsync, handles it.
In an ASP.NET Core MVC view, what does asp-for generate on input, label and validation tag helpers, and how are tag helpers switched on?
basics
~20 sasp-for binds an element to a model property: an input gets name, id, type, value and data-val attributes, a label gets for and the display name, a validation span shows that field's error. @addTagHelper in _ViewImports.cshtml enables them.
In ASP.NET Core MVC, which files does return View() search for, and when is a view in Views/Shared used instead?
basics
~20 sView() takes the view name from the action's route value and searches /Views/{controller}/{name}.cshtml, then /Views/Shared/{name}.cshtml (plus /Pages/Shared when Razor Pages are registered). A Shared view serves any controller that has no view of that name.
In ASP.NET Core, what does the [ApiController] attribute change about a controller's actions, and how do you switch each behaviour off?
basics
~20 s[ApiController] makes attribute routing mandatory, returns an automatic 400 for invalid model state, infers parameter binding sources, adds a multipart/form-data constraint for form files and turns bare 4xx results into ProblemDetails; ApiBehaviorOptions switches each off.
In a Razor view (.cshtml), how does the @ character switch from HTML to C#, and how do @if and @foreach render markup?
basics
~20 sA Razor view is HTML until an @ starts C#: @value writes an HTML-encoded value, and @if or @foreach run C# whose braces may hold HTML tags, which render as markup each time that branch or pass runs.
In Razor syntax, when does an implicit @expression end early, and when must you write an explicit @( ) expression instead?
basics
~20 sAn implicit @expression reads one identifier chain with member access, calls and indexers, and stops at a space or a character that can't continue it; use @( ) for operators, generic calls, or a value glued to preceding text.
In a Razor view, what does @ HTML-encode by default, and when do Html.Raw, HtmlString or MarkupString open an XSS hole?
basics
~20 sRazor HTML-encodes every @ value unless it is IHtmlContent; Html.Raw and HtmlString in views, or MarkupString in components, write markup unencoded, so applied to user-supplied text such as a customer note they let injected script run.
Inside a Razor code block or @foreach body in a .cshtml view, how do @: and <text> output plain text that has no HTML tag?
basics
~20 sInside @{ } or a control structure Razor reads C#, so bare text breaks the build; @: renders the rest of one line as markup, and <text>…</text> renders only its contents, across lines if needed.
In a Razor view (.cshtml), what do the @using, @inject and @functions directives add to the generated class, and how does @code differ in a component?
basics
~20 sRazor compiles a view into a class: @using adds a C# using, @inject Type Name adds a property resolved from the request's services, and @functions adds class members; @code is the component-only spelling of @functions.
In an ASP.NET Core 10 controller, how do you accept an uploaded file with IFormFile and save it to disk?
basics
~10 sPost a multipart/form-data form and declare an IFormFile parameter named like the file field. Check Length, then CopyToAsync into a FileStream under a server-generated name; the file was already buffered before the action ran.
In an ASP.NET Core 10 Minimal API, how do you register FluentValidation validators, run an injected IValidator<LoanApplication>, and return a ValidationProblem?
basics
~10 sCall AddValidatorsFromAssemblyContaining<LoanApplicationValidator>() at startup, inject IValidator<LoanApplication> into the handler, await ValidateAsync, and when IsValid is false return TypedResults.ValidationProblem(result.ToDictionary()), a 400 with validation problem details.
In ASP.NET Core 10, why does a C# property named TrackingNumber come out of an API as trackingNumber, and which other JSON defaults apply?
basics
~10 sASP.NET Core builds its System.Text.Json options from JsonSerializerDefaults.Web: property names are written in camelCase, read case-insensitively, and numbers may arrive as JSON strings. Setting PropertyNamingPolicy to null keeps the C# names.
In an ASP.NET Core MVC controller, how do [FromRoute], [FromQuery], [FromHeader] and [FromBody] decide where a stock-adjustment action's parameters come from?
basics
~20 sEach attribute pins a parameter to one source. [FromRoute], [FromQuery] and [FromHeader] read single named values from route data, the query string or a header; [FromBody] hands the whole request body to an input formatter, by default the System.Text.Json one.
In ASP.NET Core MVC, how do [Required], [StringLength], [Range] and [RegularExpression] on a sign-up model feed ModelState.IsValid, and who checks it?
basics
~20 sAfter model binding and before the action runs, MVC evaluates every validation attribute and records failures in ModelState under the property's key. In controllers with views and in Razor Pages you check ModelState.IsValid yourself; [ApiController] returns a 400 for you.
In ASP.NET Core, how do you bind the Mail section of appsettings.json to a MailOptions class and inject it into a service?
basics
~10 sRegister the section with builder.Services.Configure<MailOptions>(builder.Configuration.GetSection("Mail")) or AddOptions<MailOptions>().BindConfiguration("Mail"), then inject IOptions<MailOptions> and read .Value. Keys bind to public settable properties by name, ignoring case.
In ASP.NET Core, how do appsettings.json and appsettings.{Environment}.json combine, and how do you read a connection string from them?
basics
~10 sASP.NET Core loads appsettings.json, then appsettings.{Environment}.json, flattens both into colon-separated keys and lets the later file win key by key. GetConnectionString("Adoptions") reads ConnectionStrings:Adoptions from the merged result.
With the .NET 10 SDK, how do dotnet user-secrets init and set keep a maps API key out of source control, and where is it stored?
basics
~10 sdotnet user-secrets init writes a UserSecretsId GUID into the .csproj; dotnet user-secrets set "Maps:ApiKey" stores the value in a secrets.json file under that id in the user profile, outside the repository, as unencrypted JSON.
In ASP.NET Core, how do IOptions<T>, IOptionsSnapshot<T> and IOptionsMonitor<T> differ in lifetime and reload behaviour, and which do you inject where?
basics
~20 sIOptions<T> is a singleton computed once and never reloaded; IOptionsSnapshot<T> is scoped and recomputed per request; IOptionsMonitor<T> is a singleton whose CurrentValue updates on reload and which raises OnChange. Singletons take IOptions or IOptionsMonitor, never IOptionsSnapshot.
In ASP.NET Core, how does an environment variable like ConnectionStrings__Adoptions override appsettings.json, and what do the ASPNETCORE_ and DOTNET_ prefixes change?
basics
~20 sWebApplication.CreateBuilder loads every environment variable after the JSON files and user secrets, turning __ into the : separator, so ConnectionStrings__Adoptions overrides ConnectionStrings:Adoptions. ASPNETCORE_ and DOTNET_ variables are also loaded with the prefix stripped, but at the bottom of the chain.
In ASP.NET Core, if a controller and its service both inject the same AddScoped and AddTransient types, how many instances does one request create?
basics
~10 sOne scoped instance, shared by the controller and the service, and two transient instances, one per injection point. The request's scope disposes both kinds when the response completes; a singleton stays one instance app-wide.
In ASP.NET Core, when IPaymentGateway is registered twice with AddScoped, what does constructor injection receive, and what does IEnumerable<IPaymentGateway> receive?
basics
~10 sConstructor injection of IPaymentGateway gets the implementation from the last AddScoped call; IEnumerable<IPaymentGateway> gets one instance of every unkeyed registration, in registration order. The container raises no error about the duplicate.
In ASP.NET Core 10, what goes wrong when a singleton price cache takes a scoped DbContext in its constructor, and how do you fix it?
basics
~20 sIt is a captive dependency: the singleton keeps one DbContext for the app's lifetime. Development fails at builder.Build() with "Cannot consume scoped service"; Production starts and shares that context across concurrent requests. Create a scope per refresh with IServiceScopeFactory.
In ASP.NET Core 10, how do you choose among three keyed IPaymentGateway registrations per request, and what can go wrong with the key?
basics
~10 sRegister each gateway with AddKeyedScoped<IPaymentGateway, T>(key), then resolve at runtime with GetRequiredKeyedService<IPaymentGateway>(order.Provider) from the request's IServiceProvider. Keys match by Equals, so case or type mismatches throw InvalidOperationException.
In ASP.NET Core 10, how do you replace the built-in container through IServiceProviderFactory, and what do you lose or gain by doing it?
basics
~10 sPass an IServiceProviderFactory<TContainerBuilder> to builder.Host.UseServiceProviderFactory and add container-specific registrations in builder.Host.ConfigureContainer<TContainerBuilder>. You gain the container's extra features but lose the default factory's Development scope validation.
In ASP.NET Core 10, how do the developer exception page and UseExceptionHandler differ, and which one handles an unhandled exception in each environment?
basics
~20 sThe developer exception page shows the stack trace, headers and routing data and is added automatically in Development; UseExceptionHandler catches the exception in production and runs a safe error path, delegate or ProblemDetails writer instead.
In ASP.NET Core 10, what does AddProblemDetails() register, and what body does an API then send for an error that has no body?
basics
~10 sAddProblemDetails() registers IProblemDetailsService and a default writer as singletons. The exception handler, status-code pages, developer exception page and Problem results then write an application/problem+json body with type, title, status and a traceId.
In ASP.NET Core, how do you write and register an IExceptionHandler, and what does returning true or false from TryHandleAsync do?
basics
~20 sImplement IExceptionHandler.TryHandleAsync, register it with AddExceptionHandler<T>() and call UseExceptionHandler(). Handlers run in registration order; true means the response is written and stops the chain, false passes the exception to the next handler or the fallback.
In an ASP.NET Core 10 API, how do you use CustomizeProblemDetails to stamp every error body, and which responses does the callback reach?
basics
~10 sPass an Action<ProblemDetailsContext> to AddProblemDetails(options => options.CustomizeProblemDetails = ...). It runs after the defaults on every body IProblemDetailsService's default writer or MVC's DefaultProblemDetailsFactory builds, but not on JSON you serialize yourself.
In ASP.NET Core, how do UseStatusCodePages, UseStatusCodePagesWithRedirects and UseStatusCodePagesWithReExecute differ in what a client receives for an empty 404?
basics
~20 sAll three fill responses with status 400-599 that have no body. UseStatusCodePages writes a plain-text or ProblemDetails body in place, WithRedirects sends a 302 to an error URL, and WithReExecute runs the pipeline again at an error path while keeping the original status.
In ASP.NET Core 10, what does HttpContext carry for one request, and how do Minimal API handlers, controllers and middleware reach it?
basics
~20 sHttpContext is the object ASP.NET Core builds for one HTTP request: Request, Response, User, Items, RequestServices, RequestAborted, TraceIdentifier and the feature collection. Handlers take it as a parameter, controllers read ControllerBase.HttpContext, middleware receive it in InvokeAsync.
In ASP.NET Core 10, what must Program.cs register to use HttpContext.Session, and how does a handler store and read a value?
basics
~20 sSession needs an IDistributedCache (AddDistributedMemoryCache on one instance), AddSession and app.UseSession before the endpoints that use it. Handlers call HttpContext.Session.SetString or SetInt32 and GetString or GetInt32; ISession stores byte arrays, so objects are serialized first.
In ASP.NET Core 10, how does IHttpContextAccessor find the current request, and what does injecting it into a service cost?
basics
~20 sAddHttpContextAccessor registers a singleton HttpContextAccessor that keeps the current HttpContext in a static AsyncLocal, set when the request starts and cleared when it ends. It returns null outside a request and hides a request dependency inside the service.
In ASP.NET Core MVC or Razor Pages, when does a TempData value survive into the next request, and how do Keep and Peek change that?
basics
~20 sTempData keeps a value until a request reads it; at the end of that request read keys are removed and unread keys are saved again. Peek(key) reads without marking, Keep(key) or Keep() retains read values, and redirect results call Keep() automatically.
In ASP.NET Core, how do HttpContext.Items and HttpContext.Features differ, and when would you reach for each one?
basics
~10 sItems is an IDictionary<object, object?> for your own per-request values. Features is an IFeatureCollection keyed by interface type, through which the server and middleware expose capabilities such as IHttpRequestFeature, IHttpConnectionFeature or IHttpMaxRequestBodySizeFeature.
In ASP.NET Core, how does cookie sign-in with AddCookie and HttpContext.SignInAsync work, and how is HttpContext.User filled on the next request?
basics
~20 sAddCookie registers a handler; SignInAsync turns a ClaimsPrincipal into a protected ticket and writes it as a cookie. On later requests the authentication middleware asks the default scheme to read that cookie and sets HttpContext.User from it.
In ASP.NET Core, what do [Authorize] and [AllowAnonymous] do on controllers and actions, and how do Minimal API endpoints express the same rules?
basics
~20 s[Authorize] marks an endpoint as needing authorization: bare, it applies DefaultPolicy (an authenticated user); Policy, Roles or AuthenticationSchemes narrow it. [AllowAnonymous] switches enforcement off. Minimal APIs chain RequireAuthorization() and AllowAnonymous(), or put the same attributes on the handler.
In ASP.NET Core Identity, what do UserManager<TUser> and SignInManager<TUser> each do when a user registers and then signs in?
basics
~20 sUserManager manages stored users through a store: creating them, hashing and checking passwords, confirming e-mail, roles and lockout counts. SignInManager turns a verified user into a signed-in session by running the sign-in checks and issuing the Identity.Application cookie.
In ASP.NET Core, how do you make a Web API accept an identity provider's access tokens with AddJwtBearer, and what does the handler do?
basics
~10 sReference Microsoft.AspNetCore.Authentication.JwtBearer, call AddAuthentication().AddJwtBearer() with Authority and Audience, and mark endpoints with [Authorize] or RequireAuthorization. The handler reads the Bearer header, validates the token and puts its claims in HttpContext.User.
In ASP.NET Core, what do the default scheme settings on AddAuthentication control, and what happens when no default challenge scheme can be resolved?
basics
~20 sAuthenticationOptions holds a default scheme for each action (authenticate, challenge, forbid, sign-in, sign-out) with DefaultScheme as the fallback. If none resolves and nothing names a scheme, the call throws an InvalidOperationException saying no default scheme was found.
In ASP.NET Core Razor Pages, what protects a charity's donation form from forged cross-site posts, and what is checked when it is submitted?
basics
~20 sRazor Pages validates antiforgery tokens on every unsafe request automatically: the form carries a request token in __RequestVerificationToken, the browser returns a cookie token, and IAntiforgery checks that they pair and match the user. A failure returns 400.
In ASP.NET Core 10, how do you let a React storefront served from another origin call your API, and what does each CORS call do?
basics
~10 sRegister a policy with builder.Services.AddCors(o => o.AddPolicy("Storefront", p => p.WithOrigins("https://shop.coffee.example"))) and apply it with app.UseCors("Storefront"). The policy tells browsers which origins may read responses; it blocks no other client.
In ASP.NET Core, what is the Data Protection API for, and why does IDataProtectionProvider.CreateProtector require a purpose string?
basics
~20 sASP.NET Core's Data Protection API encrypts and authenticates payloads that leave the server, such as auth cookies, antiforgery tokens and your own tokens. The purpose string isolates them: a payload protected under one purpose throws CryptographicException when unprotected under another.
In ASP.NET Core, what do UseHttpsRedirection and UseHsts each do, and why do the web templates call UseHsts only outside Development?
basics
~10 sUseHttpsRedirection answers plain-HTTP requests with a 307 redirect to the HTTPS URL; UseHsts adds a Strict-Transport-Security header, 30 days by default, to HTTPS responses. Browsers cache HSTS, so the templates skip it in Development.
In ASP.NET Core 10, which three calls put a named fixed-window rate limit on one Minimal API endpoint, and what breaks without each?
basics
~10 sRegister a named policy with AddRateLimiter and AddFixedWindowLimiter, add the middleware with app.UseRateLimiter(), and attach the policy with RequireRateLimiting or [EnableRateLimiting]. UseRateLimiter without AddRateLimiter throws at startup; an unattached policy limits nothing.
In an ASP.NET Core 10 API using Npgsql without EF Core, how do you register a data source and run a query from a handler?
basics
~10 sAdd Npgsql.DependencyInjection, call builder.Services.AddNpgsqlDataSource(connectionString), inject NpgsqlDataSource into the handler, and open a pooled connection per query with await using var conn = await dataSource.OpenConnectionAsync(); disposing it hands the connection back to the pool.
In ASP.NET Core 10, how do you register an EF Core DbContext with a connection string from configuration, and what lifetime does it get?
basics
~10 sCall builder.Services.AddDbContext<BookingDbContext>(o => o.UseNpgsql(builder.Configuration.GetConnectionString("Bookings"))) before Build(). AddDbContext registers the context Scoped by default, so every HTTP request gets its own instance, disposed when that request ends.
With Microsoft.Data.SqlClient in an ASP.NET Core app, what do new SqlConnection(cs), OpenAsync and DisposeAsync actually do when pooling is on?
basics
~20 sConstructing a SqlConnection allocates only an object. OpenAsync borrows an idle physical connection from the pool for that exact connection string, creating one only if none is free, and DisposeAsync returns it to the pool rather than closing it.
In ASP.NET Core, why is the DbContext that AddDbContext registers scoped, and what breaks if you pass ServiceLifetime.Transient or ServiceLifetime.Singleton instead?
basics
~20 sScoped gives each request exactly one context, so every service in that request shares one change tracker and one SaveChangesAsync. Transient splits a request's work across trackers; singleton shares one non-thread-safe context across concurrent requests.
In ASP.NET Core 10, how should Dapper code obtain its IDbConnection: an injected DbDataSource, a registered connection, or new SqlConnection per call?
basics
~20 sInject a singleton DbDataSource and open a DbConnection per query with await using; Dapper's extension methods take it as an IDbConnection. Never share one connection through a singleton, and note AddNpgsqlDataSource registers DbConnection, not IDbConnection.
In ASP.NET Core, what is IDistributedCache, why does it deal in byte arrays, and how do you back it with Redis?
basics
~20 sIDistributedCache is ASP.NET Core's abstraction over a cache that lives outside the web process, so every instance reads the same entry. It stores byte arrays under string keys; you serialize objects yourself and register Redis with AddStackExchangeRedisCache.
In ASP.NET Core 10, what is HybridCache, how do you register it with AddHybridCache, and what does GetOrCreateAsync do on a miss?
basics
~10 sHybridCache is a two-tier cache: an in-process IMemoryCache in front of any registered IDistributedCache. AddHybridCache registers it; GetOrCreateAsync checks memory, then the distributed store, then runs your factory once and writes both tiers.
In ASP.NET Core's IMemoryCache, how do absolute and sliding expiration differ, and why would you set both on one entry?
basics
~20 sAbsolute expiration removes an entry at a fixed time no matter how often it is read; sliding expiration removes it after a period with no reads. Sliding alone can keep a hot entry forever, so an absolute cap bounds staleness.
In ASP.NET Core, how do you register IMemoryCache and read or write an entry with TryGetValue and Set, and where does that data live?
basics
~20 sCall builder.Services.AddMemoryCache(), inject IMemoryCache, read with TryGetValue (a bool plus an out value) and write with Set. Entries are object references in that server process's heap: every instance keeps its own copy, lost on restart.
In ASP.NET Core, what does output caching do, and why do AddOutputCache and UseOutputCache on their own cache no responses?
basics
~20 sOutput caching stores an endpoint's whole response (status, headers and body) on the server and replays it without running the endpoint. AddOutputCache and UseOutputCache only make it available; nothing is cached until a policy applies to the request.
In ASP.NET Core 10, how do you expose a health endpoint with AddHealthChecks and MapHealthChecks, and what does it return?
basics
~10 sCall builder.Services.AddHealthChecks() and app.MapHealthChecks("/healthz"). The endpoint runs every registered check and writes Healthy, Degraded or Unhealthy as plain text, with 200 for Healthy and Degraded and 503 for Unhealthy.
In ASP.NET Core 10, how do you enable HTTP logging, what does it log by default, and why might a template app log nothing?
basics
~10 sCall builder.Services.AddHttpLogging() and app.UseHttpLogging(). By default it logs request method, path, protocol, scheme and headers, plus status code and response headers, at Information; the template's Microsoft.AspNetCore = Warning filters all of it out.
In ASP.NET Core 10, how do you inject ILogger<T>, which category does it log under, and how does Logging:LogLevel in appsettings.json decide what is written?
basics
~10 sInject ILogger<PickListService> through the constructor; its category is the type's full name, such as Warehouse.Picking.PickListService. Logging:LogLevel maps category prefixes to minimum levels: the longest matching prefix wins, otherwise Default applies.
In ASP.NET Core 10, how do you serve separate liveness and readiness endpoints for a Kubernetes-hosted API using check tags and HealthCheckOptions.Predicate?
basics
~10 sTag each registration, for example AddCheck("self", ..., tags: ["live"]) and AddDbContextCheck<ParkingDbContext>(tags: ["ready"]), then map two endpoints whose HealthCheckOptions.Predicate selects by tag: r => r.Tags.Contains("live") and r => r.Tags.Contains("ready").
In ASP.NET Core, why pass a message template with arguments to logger.LogInformation instead of an interpolated $"..." string, and how do placeholders bind?
basics
~20 sA template such as "Picked {Sku} for order {OrderId}" keeps Sku, OrderId and the template as named values that providers can emit as fields. An interpolated string arrives as one finished text, built even when the level is filtered out.
In ASP.NET Core 10, how do you host a gRPC service defined in a .proto file, and what do Grpc.Tools, AddGrpc and MapGrpcService each do?
basics
~10 sReference Grpc.AspNetCore, add the .proto as a <Protobuf> item so Grpc.Tools generates a base class at build time, override its methods, then call builder.Services.AddGrpc() and app.MapGrpcService<T>(). Calls must arrive over HTTP/2.
In an ASP.NET Core 10 Minimal API, what goes wrong when GET /employees/{id} returns the EF Core Employee entity instead of an EmployeeDto record?
basics
~20 sReturning the entity hands System.Text.Json every public property, so Salary and any column added later leak, loaded navigations can throw an object-cycle JsonException, and the JSON contract changes whenever the table does. A response record lists exactly what is public.
In ASP.NET Core 10, what do AddOpenApi and MapOpenApi do, and at which URL is the default OpenAPI document served?
basics
~20 sAddOpenApi registers ASP.NET Core's built-in OpenAPI generator for a document named v1, and MapOpenApi adds a GET endpoint that builds and serves it at /openapi/v1.json. The webapi template maps it only in Development and ships no UI.
In ASP.NET Core, how do you add API versioning with the Asp.Versioning 10 packages, and what do its defaults do with an unversioned request?
basics
~20 sAsp.Versioning.Http (Minimal APIs) or Asp.Versioning.Mvc (controllers, via .AddMvc()) plus services.AddApiVersioning(). By default versions come from the api-version query parameter or a URL segment, nothing is assumed, so a request to a versioned endpoint without a version gets 400.
In ASP.NET Core with EF Core, why does a PUT handler that binds the body to the Employee entity and calls db.Update let a caller rewrite Salary?
basics
~20 sThe JSON body is deserialized straight onto Employee, so any property the caller sends, Salary included, is set, and any it omits arrives as a default. db.Update then marks every column modified, so SaveChanges writes both into the row.
In ASP.NET Core, why should outgoing HTTP calls go through IHttpClientFactory and AddHttpClient rather than a new HttpClient per call or one static instance?
basics
~20 sAn HttpClient's handler owns its connection pool. A new client per call discards connections and can exhaust sockets; one static client can miss DNS changes. IHttpClientFactory pools handlers per name and rotates them every two minutes by default.
In an ASP.NET Core 10 app, how do you give an HttpClient automatic retries for transient failures, and which package provides them?
basics
~10 sAdd the Microsoft.Extensions.Http.Resilience package and chain AddStandardResilienceHandler() onto the client's AddHttpClient registration. It retries 5xx, 408 and 429 responses and HttpRequestException, alongside a circuit breaker and timeouts, built on Polly 8.
In ASP.NET Core, how does a named HttpClient registered with AddHttpClient differ from a typed client, and when would you choose each?
basics
~20 sA named client is configuration stored under a string and fetched with IHttpClientFactory.CreateClient(name). A typed client is a class whose constructor receives a configured HttpClient; DI injects the class itself, registered transient. Typed clients suit one downstream API wrapped in methods.
In ASP.NET Core, which five strategies does AddStandardResilienceHandler stack, in what order from the outermost, and why does that order matter?
basics
~20 sFrom the outside in: rate limiter, total request timeout (30 s), retry, circuit breaker, attempt timeout (10 s). The total timeout bounds every retry, the breaker counts each attempt, and an open breaker fails fast because its rejection is not retried.
In ASP.NET Core, how does a DelegatingHandler add an auth header to a typed HttpClient's requests, and which DI scope does it live in?
basics
~20 sDerive from DelegatingHandler, set the header in SendAsync and call base.SendAsync; register it transient and chain AddHttpMessageHandler<T>() on the client. The factory resolves it from its own handler scope, which lives as long as the handler chain, not the incoming request.
In ASP.NET Core 10, how do you stream Server-Sent Events with TypedResults.ServerSentEvents, and what does the result set up for you?
basics
~10 sReturn TypedResults.ServerSentEvents(items), where items is an IAsyncEnumerable<T> or IAsyncEnumerable<SseItem<T>>. The ServerSentEventsResult<T> sets the event-stream and no-cache headers, disables buffering, serializes each item as JSON (strings raw) and writes it as it is yielded.
In ASP.NET Core 10, how do you accept a raw WebSocket without SignalR, and why must the handler stay running until it closes?
basics
~10 sCall app.UseWebSockets(), then in the endpoint check context.WebSockets.IsWebSocketRequest and await AcceptWebSocketAsync() to get a WebSocket. The handler must await its receive/send loop, because returning ends the request and tears the socket down.
In an ASP.NET Core raw WebSocket handler, how should the receive loop assemble messages and finish the close handshake cleanly?
basics
~10 sLoop on ReceiveAsync into a buffer, appending Count bytes until EndOfMessage, then handle the message. When MessageType is Close, answer with CloseAsync and exit; an abrupt disconnect surfaces as a WebSocketException to catch.
Without TypedResults.ServerSentEvents, how do you hand-write a Server-Sent Events response in ASP.NET Core, and what must each write do?
basics
~20 sSet ContentType to text/event-stream and Cache-Control to no-cache before writing, call DisableBuffering, then for each event write data: lines ending in a blank line and make sure the bytes are flushed, looping until the request's token is cancelled.
With ASP.NET Core 10's TypedResults.ServerSentEvents, how do SseItem<T> event types and ids let a build dashboard resume after a reconnect?
basics
~20 sYield SseItem<T> objects: the constructor takes the data and an event type, and EventId and ReconnectionInterval are init properties. A reconnecting client sends the last id back in a Last-Event-ID header, which the endpoint binds and uses to replay later events.
In ASP.NET Core, what is the difference between implementing IHostedService directly and deriving from BackgroundService, and how is either one registered?
basics
~10 sIHostedService gives you StartAsync and StopAsync and nothing else; BackgroundService implements both and asks only for ExecuteAsync(stoppingToken), the long-running loop. Either is registered with builder.Services.AddHostedService<T>(), which adds a singleton.
In an ASP.NET Core BackgroundService, how should ExecuteAsync use its stoppingToken, and what happens at shutdown when the loop ignores it?
basics
~20 sstoppingToken is cancelled when the host calls StopAsync, so the loop checks it and passes it to every awaited call. A loop that ignores it keeps running until the shutdown timeout, then is cut off mid-work when the process exits.
For an ASP.NET Core work queue on System.Threading.Channels, when do you choose CreateBounded over CreateUnbounded, and what does BoundedChannelFullMode control?
basics
~20 sChoose CreateBounded for any queue fed by HTTP traffic, because an unbounded channel grows until memory runs out. BoundedChannelFullMode decides what a write does when the channel is full: Wait (the default) waits for room; DropNewest, DropOldest and DropWrite discard an item.
In ASP.NET Core, how do you hand work from an endpoint to a background consumer using a System.Threading.Channels Channel<T>?
basics
~10 sRegister one Channel<T> as a singleton. The endpoint writes a job with channel.Writer.WriteAsync and returns 202 Accepted; a BackgroundService reads jobs one by one with await foreach over channel.Reader.ReadAllAsync(stoppingToken).
What changed in .NET 10 about how BackgroundService.ExecuteAsync starts, and where should ASP.NET Core start-up work that must finish before requests go?
basics
~20 sIn .NET 10 BackgroundService runs all of ExecuteAsync inside Task.Run, so code before the first await no longer blocks start-up. Work that must finish before requests arrive goes in an overridden StartAsync or IHostedLifecycleService.StartingAsync instead.
In ASP.NET Core 10, what must RequestLocalizationOptions declare before UseRequestLocalization serves French and German, and what happens when you skip it?
basics
~20 sRequestLocalizationOptions needs SupportedCultures, SupportedUICultures and a default culture. Both lists default to the server's own culture only, so without them every French or German request is treated as unsupported and served in the server's culture.
In ASP.NET Core 10, how do AddLocalization and IStringLocalizer<T> return a French or German string, and what comes back when no translation exists?
basics
~10 sAddLocalization registers IStringLocalizer<T>, which reads the .resx resources named after T for CultureInfo.CurrentUICulture. Its indexer returns a LocalizedString; when no resource holds the key, Value is the key itself and ResourceNotFound is true.
In ASP.NET Core request localization, in what order do the default culture providers run, and when does a provider's answer win?
basics
~10 sRequestCultureProviders runs QueryStringRequestCultureProvider, CookieRequestCultureProvider, then AcceptLanguageHeaderRequestCultureProvider. The first provider that returns a culture found in the supported lists, directly or through a parent, wins; if none does, DefaultRequestCulture applies.
How do you build an ASP.NET Core language switcher that remembers the visitor's choice with CookieRequestCultureProvider.MakeCookieValue?
basics
~10 sAppend the .AspNetCore.Culture cookie with CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)), which writes c=fr|uic=fr, after checking the culture is supported, then redirect locally. CookieRequestCultureProvider reads it on the following requests.
In ASP.NET Core request localization, how do SupportedCultures and SupportedUICultures differ, and when should the two lists hold different cultures?
basics
~10 sSupportedCultures limits CurrentCulture, which formats dates, numbers and currency and drives culture-aware comparison; SupportedUICultures limits CurrentUICulture, which chooses translated resources. Regional sites list many specific cultures for formatting and a few languages for text.
In ASP.NET Core 10, what does WebApplicationFactory<Program> do when a test calls CreateClient, and what must the projects provide?
basics
~20 sWebApplicationFactory<Program> runs the app's real Program.cs inside the test process, swaps the server for an in-memory TestServer and returns an HttpClient wired to it, so requests cross the whole middleware pipeline without opening a socket.
With Bogus, how do you build a Faker<Patient> that generates realistic patient records for an ASP.NET Core clinic-scheduling test suite?
basics
~10 sCreate new Faker<Patient>() and add a RuleFor per property, drawing values from the Faker hub (f.Name.FirstName(), f.Internet.Email(...), f.Date.PastDateOnly(...)). Generate() returns one patient and Generate(50) a list; StrictMode(true) fails when a property has no rule.
With Moq 4.21, how do you stub a coupon repository and verify an event was published when unit testing a grocery app's discount handler?
basics
~20 sCreate a Mock<ICouponRepository>, Setup the lookup with It.IsAny<CancellationToken>() and ReturnsAsync(coupon), pass mock.Object to the handler, then call Verify on the event publisher's mock with Times.Once(). Calls you never set up return defaults rather than failing.
How do you run ASP.NET Core integration tests for an order-management API against a real PostgreSQL started with Testcontainers?
basics
~10 sStart a Testcontainers PostgreSqlBuilder container with a pinned image once per test run, pass its GetConnectionString() to WebApplicationFactory<Program> as the app's connection string, apply migrations once, and reset the data between tests.
In an ASP.NET Core 10 WebApplicationFactory test, how do you replace the job-board API's registered e-mail sender with a fake for one test?
basics
~10 sCall factory.WithWebHostBuilder(b => b.ConfigureTestServices(s => { s.RemoveAll<IMailSender>(); s.AddSingleton<IMailSender>(fake); })). The callback runs after Program.cs's registrations, and the derived factory boots its own app, leaving the shared factory untouched.
In ASP.NET Core 10, what is Native AOT publishing, and what do you gain and give up compared with a normal JIT-compiled app?
basics
~20 sNative AOT, switched on with PublishAot in the project file, compiles the app into one native executable at publish time. It starts faster, uses less memory and needs no installed runtime, but loses runtime reflection and code generation, MVC and cross-OS publishing.
In ASP.NET Core 10, what is the difference between framework-dependent and self-contained publish output, and which one does dotnet publish produce by default?
basics
~20 sFramework-dependent output, the default, holds only the app and its dependencies and runs on an installed .NET and ASP.NET Core runtime that it rolls forward to the latest patch. Self-contained output also ships the runtime: bigger, platform-specific, patched only by republishing.
In an ASP.NET Core 10 endpoint, why is calling .Result or .Wait() on a Task harmful, and what should you write instead?
basics
~20 sBlocking on .Result or .Wait() parks a thread-pool thread until the awaited I/O finishes, so under load ASP.NET Core runs out of free threads and every request slows down. Make the handler async and await the call instead.
With the .NET 10 SDK, how does dotnet publish /t:PublishContainer build an ASP.NET Core image without a Dockerfile, and what defaults does it apply?
basics
~20 sPublishContainer publishes the app and layers the output onto an inferred Microsoft base image (aspnet:10.0 for a web app), with no Dockerfile. It names the image after the assembly, tags it latest, and takes user and port from the base image.
Your team sets PublishAot on an existing ASP.NET Core 10 API built with controllers and Session; what breaks, and how do IL2026 and IL3050 warnings flag it first?
basics
~20 sMVC controllers and Session are not supported under Native AOT: AddControllers and AddSession carry RequiresUnreferencedCode, so the build reports IL2026, and calls marked RequiresDynamicCode report IL3050. Publish rescans every package; any warning means the native app may fail at run time.
In an ASP.NET Core clean-architecture solution split into Web, Application, Domain and Infrastructure projects, what belongs in each project and which project references which?
basics
~20 sDomain holds entities and rules and references nothing. Application holds use cases and the interfaces they need, referencing Domain. Infrastructure implements those interfaces with EF Core and references Application. Web hosts Program.cs and the endpoints, referencing Application and Infrastructure.
In an ASP.NET Core modular monolith, what do a module's AddX and MapX extension methods look like, and why should Program.cs call only those?
basics
~20 sAddX is a public static extension on IServiceCollection that registers the module's internal services, options and DbContext and returns the collection; MapX extends IEndpointRouteBuilder and maps its endpoints. Program.cs calls only these, so module internals stay hidden and movable.
In an ASP.NET Core vertical-slice layout, what does one feature folder contain, and what makes a Minimal API endpoint over its handler thin?
basics
~20 sA feature folder holds everything for one use case: the request and response types, the handler with its data access, validation and the endpoint mapping. A thin endpoint only binds input, calls the handler and turns its outcome into TypedResults.
In an ASP.NET Core modular monolith on EF Core 10, why give each module its own DbContext and schema, and how do modules then read each other's data?
basics
~20 sA DbContext per module, with HasDefaultSchema and its own migrations history table, keeps each module's tables and migrations private and extractable. Other modules never query those tables; they call the owning module's public contract or keep their own copy updated by events.
In an ASP.NET Core solution, how do ProjectReference items enforce clean-architecture dependency direction, and where can that enforcement still leak?
basics
~20 sA project can only compile against projects it references, so inward-only ProjectReference items stop Domain from naming a DbContext, and a reverse reference fails restore with NU1108. It leaks through transitive references, public Infrastructure types reachable from Web, and package references.