skip to content

ASP.NET Core

2 roadmaps431 questionsupdated

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 pageshow

guide

overview

~2 min

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

  1. Project Setup & Startup →

    Program.cs, WebApplicationBuilder and environments: the startup every other section takes for granted, and where many interviews open.

  2. HTTP Pipeline Composition →

    How the request pipeline is composed and why order matters; the source of most misconfiguration questions.

  3. IServiceCollection Wiring →

    Registration and lifetimes, so you can say who shares an instance and spot a captive dependency.

  4. Configuration Sources & Options →

    Which configuration source wins and which options interface to inject; needed before hosting, auth or caching settings make sense.

  5. Model Binding Pipeline →

    How request data becomes typed parameters and how bad input turns into a 400, under both handler styles.

  6. Sign-In & Permissions →

    Schemes, tokens and policies; it builds on the pipeline order and endpoint metadata covered in the earlier steps.

  • Putting UseAuthorization before UseAuthentication, 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 DbContext in 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 .Result or .Wait() in request code; it passes every test at low traffic and starves the thread pool under real load.

  • Creating a new HttpClient for each outgoing call; under load it can exhaust sockets. Register clients with AddHttpClient and 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

report an issue with this guide →

questions

431 · 25 sections

In ASP.NET Core 10, which environment does an app run in when nothing sets one, and where does Development come from locally?

level: juniorimportance: must knowfreq 76%
basics
~20 s

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

open as a page

In an ASP.NET Core 10 Program.cs, what do WebApplication.CreateBuilder(args), builder.Build() and app.Run() each do?

level: juniorimportance: must knowfreq 76%
basics
~20 s

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

open as a page

For ASP.NET Core on .NET, what is the difference between an LTS and an STS release, and how long is each supported?

level: juniorimportance: must knowfreq 68%
basics
~20 s

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

open as a page

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?

level: juniorimportance: must knowfreq 72%
basics
~20 s

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

open as a page

How do you upgrade an ASP.NET Core 8 web app to .NET 10, and what has to change besides the TargetFramework?

level: middleimportance: must knowfreq 60%
basics
~20 s

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

open as a page

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?

level: juniorimportance: must knowfreq 50%
basics
~20 s

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

open as a page

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?

level: juniorimportance: must knowfreq 62%
basics
~10 s

With 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).

open as a page

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?

level: juniorimportance: must knowfreq 55%
basics
~20 s

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

open as a page

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?

level: middleimportance: must knowfreq 50%
basics
~10 s

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

open as a page

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?

level: juniorimportance: should knowfreq 40%
basics
~10 s

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

open as a page

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?

level: juniorimportance: must knowfreq 55%
basics
~20 s

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

open as a page

In ASP.NET Core, what shape must a convention-based middleware class have, and how do you add it to the request pipeline?

level: juniorimportance: must knowfreq 70%
basics
~10 s

A 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().

open as a page

In ASP.NET Core, what is a RequestDelegate, and how do app.Use and app.Run differ when you build the request pipeline?

level: juniorimportance: must knowfreq 78%
basics
~10 s

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

open as a page

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?

level: juniorimportance: must knowfreq 70%
basics
~20 s

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

open as a page

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?

level: middleimportance: must knowfreq 66%
basics
~20 s

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

open as a page

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?

level: juniorimportance: must knowfreq 68%
basics
~20 s

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

open as a page

In ASP.NET Core, what do UseRouting and UseEndpoints each do, and why does middleware placed before UseRouting get null from HttpContext.GetEndpoint()?

level: middleimportance: must knowfreq 58%
basics
~10 s

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

open as a page

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?

level: middleimportance: must knowfreq 60%
basics
~20 s

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

open as a page

In ASP.NET Core Minimal APIs, what does app.MapGroup("/api/v1/fleet") return, and how does it apply conventions once to many endpoints?

level: juniorimportance: must knowfreq 60%
basics
~20 s

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

open as a page

In an ASP.NET Core Minimal API, how does a MapGet or MapPost handler decide where each of its parameters is bound from?

level: juniorimportance: must knowfreq 72%
basics
~20 s

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

open as a page

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?

level: juniorimportance: must knowfreq 66%
basics
~10 s

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

open as a page

In ASP.NET Core 10 Minimal APIs, what does builder.Services.AddValidation() do, and what happened to DataAnnotations on handler parameters before it?

level: juniorimportance: must knowfreq 55%
basics
~20 s

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

open as a page

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?

level: middleimportance: must knowfreq 55%
basics
~10 s

Implement 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).

open as a page

In ASP.NET Core, when should a controller derive from ControllerBase instead of Controller, and which of AddControllers, AddControllersWithViews or AddMvc does it need?

level: juniorimportance: must knowfreq 80%
basics
~10 s

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

open as a page

In ASP.NET Core Razor Pages, how do the @page directive, the Pages folder and OnGet or OnPost methods route a request to code?

level: juniorimportance: must knowfreq 62%
basics
~20 s

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

open as a page

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?

level: juniorimportance: must knowfreq 66%
basics
~20 s

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

open as a page

In ASP.NET Core MVC, which files does return View() search for, and when is a view in Views/Shared used instead?

level: juniorimportance: must knowfreq 68%
basics
~20 s

View() 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.

open as a page

In ASP.NET Core, what does the [ApiController] attribute change about a controller's actions, and how do you switch each behaviour off?

level: middleimportance: must knowfreq 75%
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.

open as a page

In a Razor view (.cshtml), how does the @ character switch from HTML to C#, and how do @if and @foreach render markup?

level: juniorimportance: must knowfreq 62%
basics
~20 s

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

open as a page

In Razor syntax, when does an implicit @expression end early, and when must you write an explicit @( ) expression instead?

level: middleimportance: must knowfreq 55%
basics
~20 s

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

open as a page

In a Razor view, what does @ HTML-encode by default, and when do Html.Raw, HtmlString or MarkupString open an XSS hole?

level: seniorimportance: must knowfreq 58%
basics
~20 s

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

open as a page

Inside a Razor code block or @foreach body in a .cshtml view, how do @: and <text> output plain text that has no HTML tag?

level: middleimportance: should knowfreq 30%
basics
~20 s

Inside @{ } 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.

open as a page

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?

level: seniorimportance: should knowfreq 33%
basics
~20 s

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

open as a page

In an ASP.NET Core 10 controller, how do you accept an uploaded file with IFormFile and save it to disk?

level: juniorimportance: must knowfreq 62%
basics
~10 s

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

open as a page

In an ASP.NET Core 10 Minimal API, how do you register FluentValidation validators, run an injected IValidator<LoanApplication>, and return a ValidationProblem?

level: juniorimportance: must knowfreq 62%
basics
~10 s

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

open as a page

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?

level: juniorimportance: must knowfreq 62%
basics
~10 s

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

open as a page

In an ASP.NET Core MVC controller, how do [FromRoute], [FromQuery], [FromHeader] and [FromBody] decide where a stock-adjustment action's parameters come from?

level: juniorimportance: must knowfreq 78%
basics
~20 s

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

open as a page

In ASP.NET Core MVC, how do [Required], [StringLength], [Range] and [RegularExpression] on a sign-up model feed ModelState.IsValid, and who checks it?

level: juniorimportance: must knowfreq 82%
basics
~20 s

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

open as a page

In ASP.NET Core, how do you bind the Mail section of appsettings.json to a MailOptions class and inject it into a service?

level: juniorimportance: must knowfreq 74%
basics
~10 s

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

open as a page

In ASP.NET Core, how do appsettings.json and appsettings.{Environment}.json combine, and how do you read a connection string from them?

level: juniorimportance: must knowfreq 78%
basics
~10 s

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

open as a page

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?

level: juniorimportance: must knowfreq 72%
basics
~10 s

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

open as a page

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?

level: middleimportance: must knowfreq 80%
basics
~20 s

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

open as a page

In ASP.NET Core, how does an environment variable like ConnectionStrings__Adoptions override appsettings.json, and what do the ASPNETCORE_ and DOTNET_ prefixes change?

level: middleimportance: must knowfreq 70%
basics
~20 s

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

open as a page

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?

level: juniorimportance: must knowfreq 82%
basics
~10 s

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

open as a page

In ASP.NET Core, when IPaymentGateway is registered twice with AddScoped, what does constructor injection receive, and what does IEnumerable<IPaymentGateway> receive?

level: juniorimportance: must knowfreq 62%
basics
~10 s

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

open as a page

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?

level: middleimportance: must knowfreq 72%
basics
~20 s

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

open as a page

In ASP.NET Core 10, how do you choose among three keyed IPaymentGateway registrations per request, and what can go wrong with the key?

level: middleimportance: must knowfreq 54%
basics
~10 s

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

open as a page

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?

level: seniorimportance: must knowfreq 45%
basics
~10 s

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

open as a page

In ASP.NET Core 10, how do the developer exception page and UseExceptionHandler differ, and which one handles an unhandled exception in each environment?

level: juniorimportance: must knowfreq 78%
basics
~20 s

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

open as a page

In ASP.NET Core 10, what does AddProblemDetails() register, and what body does an API then send for an error that has no body?

level: juniorimportance: must knowfreq 68%
basics
~10 s

AddProblemDetails() 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.

open as a page

In ASP.NET Core, how do you write and register an IExceptionHandler, and what does returning true or false from TryHandleAsync do?

level: middleimportance: must knowfreq 68%
basics
~20 s

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

open as a page

In an ASP.NET Core 10 API, how do you use CustomizeProblemDetails to stamp every error body, and which responses does the callback reach?

level: middleimportance: must knowfreq 55%
basics
~10 s

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

open as a page

In ASP.NET Core, how do UseStatusCodePages, UseStatusCodePagesWithRedirects and UseStatusCodePagesWithReExecute differ in what a client receives for an empty 404?

level: middleimportance: should knowfreq 45%
basics
~20 s

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

open as a page

In ASP.NET Core 10, what does HttpContext carry for one request, and how do Minimal API handlers, controllers and middleware reach it?

level: juniorimportance: must knowfreq 66%
basics
~20 s

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

open as a page

In ASP.NET Core 10, what must Program.cs register to use HttpContext.Session, and how does a handler store and read a value?

level: juniorimportance: must knowfreq 58%
basics
~20 s

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

open as a page

In ASP.NET Core 10, how does IHttpContextAccessor find the current request, and what does injecting it into a service cost?

level: middleimportance: must knowfreq 58%
basics
~20 s

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

open as a page

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?

level: middleimportance: must knowfreq 50%
basics
~20 s

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

open as a page

In ASP.NET Core, how do HttpContext.Items and HttpContext.Features differ, and when would you reach for each one?

level: middleimportance: should knowfreq 45%
basics
~10 s

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

open as a page

In ASP.NET Core, what do [Authorize] and [AllowAnonymous] do on controllers and actions, and how do Minimal API endpoints express the same rules?

level: juniorimportance: must knowfreq 80%
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.

open as a page

In ASP.NET Core Identity, what do UserManager<TUser> and SignInManager<TUser> each do when a user registers and then signs in?

level: juniorimportance: must knowfreq 68%
basics
~20 s

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

open as a page

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?

level: juniorimportance: must knowfreq 78%
basics
~10 s

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

open as a page

In ASP.NET Core, what do the default scheme settings on AddAuthentication control, and what happens when no default challenge scheme can be resolved?

level: middleimportance: must knowfreq 60%
basics
~20 s

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

open as a page

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?

level: juniorimportance: must knowfreq 66%
basics
~20 s

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

open as a page

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?

level: juniorimportance: must knowfreq 78%
basics
~10 s

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

open as a page

In ASP.NET Core, what is the Data Protection API for, and why does IDataProtectionProvider.CreateProtector require a purpose string?

level: juniorimportance: must knowfreq 45%
basics
~20 s

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

open as a page

In ASP.NET Core, what do UseHttpsRedirection and UseHsts each do, and why do the web templates call UseHsts only outside Development?

level: juniorimportance: must knowfreq 64%
basics
~10 s

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

open as a page

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?

level: juniorimportance: must knowfreq 45%
basics
~10 s

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

open as a page

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?

level: juniorimportance: must knowfreq 60%
basics
~10 s

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

open as a page

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?

level: juniorimportance: must knowfreq 80%
basics
~10 s

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

open as a page

With Microsoft.Data.SqlClient in an ASP.NET Core app, what do new SqlConnection(cs), OpenAsync and DisposeAsync actually do when pooling is on?

level: middleimportance: must knowfreq 58%
basics
~20 s

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

open as a page

In ASP.NET Core, why is the DbContext that AddDbContext registers scoped, and what breaks if you pass ServiceLifetime.Transient or ServiceLifetime.Singleton instead?

level: middleimportance: must knowfreq 70%
basics
~20 s

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

open as a page

In ASP.NET Core 10, how should Dapper code obtain its IDbConnection: an injected DbDataSource, a registered connection, or new SqlConnection per call?

level: middleimportance: should knowfreq 45%
basics
~20 s

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

open as a page

In ASP.NET Core, what is IDistributedCache, why does it deal in byte arrays, and how do you back it with Redis?

level: juniorimportance: must knowfreq 62%
basics
~20 s

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

open as a page

In ASP.NET Core 10, what is HybridCache, how do you register it with AddHybridCache, and what does GetOrCreateAsync do on a miss?

level: juniorimportance: must knowfreq 52%
basics
~10 s

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

open as a page

In ASP.NET Core's IMemoryCache, how do absolute and sliding expiration differ, and why would you set both on one entry?

level: juniorimportance: must knowfreq 58%
basics
~20 s

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

open as a page

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?

level: juniorimportance: must knowfreq 64%
basics
~20 s

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

open as a page

In ASP.NET Core, what does output caching do, and why do AddOutputCache and UseOutputCache on their own cache no responses?

level: juniorimportance: must knowfreq 56%
basics
~20 s

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

open as a page

In ASP.NET Core 10, how do you expose a health endpoint with AddHealthChecks and MapHealthChecks, and what does it return?

level: juniorimportance: must knowfreq 70%
basics
~10 s

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

open as a page

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?

level: juniorimportance: must knowfreq 50%
basics
~10 s

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

open as a page

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?

level: juniorimportance: must knowfreq 78%
basics
~10 s

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

open as a page

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?

level: middleimportance: must knowfreq 60%
basics
~10 s

Tag 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").

open as a page

In ASP.NET Core, why pass a message template with arguments to logger.LogInformation instead of an interpolated $"..." string, and how do placeholders bind?

level: middleimportance: must knowfreq 64%
basics
~20 s

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

open as a page

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?

level: juniorimportance: must knowfreq 50%
basics
~10 s

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

open as a page

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?

level: juniorimportance: must knowfreq 72%
basics
~20 s

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

open as a page

In ASP.NET Core 10, what do AddOpenApi and MapOpenApi do, and at which URL is the default OpenAPI document served?

level: juniorimportance: must knowfreq 70%
basics
~20 s

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

open as a page

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?

level: juniorimportance: must knowfreq 55%
basics
~20 s

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

open as a page

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?

level: middleimportance: must knowfreq 55%
basics
~20 s

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

open as a page

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?

level: juniorimportance: must knowfreq 80%
basics
~20 s

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

open as a page

In an ASP.NET Core 10 app, how do you give an HttpClient automatic retries for transient failures, and which package provides them?

level: juniorimportance: must knowfreq 58%
basics
~10 s

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

open as a page

In ASP.NET Core, how does a named HttpClient registered with AddHttpClient differ from a typed client, and when would you choose each?

level: middleimportance: must knowfreq 66%
basics
~20 s

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

open as a page

In ASP.NET Core, which five strategies does AddStandardResilienceHandler stack, in what order from the outermost, and why does that order matter?

level: middleimportance: must knowfreq 50%
basics
~20 s

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

open as a page

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?

level: middleimportance: should knowfreq 52%
basics
~20 s

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

open as a page

In ASP.NET Core 10, how do you stream Server-Sent Events with TypedResults.ServerSentEvents, and what does the result set up for you?

level: juniorimportance: must knowfreq 50%
basics
~10 s

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

open as a page

In ASP.NET Core 10, how do you accept a raw WebSocket without SignalR, and why must the handler stay running until it closes?

level: juniorimportance: must knowfreq 58%
basics
~10 s

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

open as a page

In an ASP.NET Core raw WebSocket handler, how should the receive loop assemble messages and finish the close handshake cleanly?

level: middleimportance: must knowfreq 50%
basics
~10 s

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

open as a page

Without TypedResults.ServerSentEvents, how do you hand-write a Server-Sent Events response in ASP.NET Core, and what must each write do?

level: middleimportance: should knowfreq 30%
basics
~20 s

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

open as a page

With ASP.NET Core 10's TypedResults.ServerSentEvents, how do SseItem<T> event types and ids let a build dashboard resume after a reconnect?

level: middleimportance: should knowfreq 38%
basics
~20 s

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

open as a page

In ASP.NET Core, what is the difference between implementing IHostedService directly and deriving from BackgroundService, and how is either one registered?

level: juniorimportance: must knowfreq 62%
basics
~10 s

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

open as a page

In an ASP.NET Core BackgroundService, how should ExecuteAsync use its stoppingToken, and what happens at shutdown when the loop ignores it?

level: middleimportance: must knowfreq 55%
basics
~20 s

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

open as a page

For an ASP.NET Core work queue on System.Threading.Channels, when do you choose CreateBounded over CreateUnbounded, and what does BoundedChannelFullMode control?

level: middleimportance: must knowfreq 52%
basics
~20 s

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

open as a page

In ASP.NET Core, how do you hand work from an endpoint to a background consumer using a System.Threading.Channels Channel<T>?

level: juniorimportance: should knowfreq 45%
basics
~10 s

Register 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).

open as a page

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?

level: middleimportance: should knowfreq 32%
basics
~20 s

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

open as a page

In ASP.NET Core 10, what must RequestLocalizationOptions declare before UseRequestLocalization serves French and German, and what happens when you skip it?

level: juniorimportance: must knowfreq 55%
basics
~20 s

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

open as a page

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?

level: juniorimportance: must knowfreq 62%
basics
~10 s

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

open as a page

In ASP.NET Core request localization, in what order do the default culture providers run, and when does a provider's answer win?

level: middleimportance: must knowfreq 50%
basics
~10 s

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

open as a page

In ASP.NET Core request localization, how do SupportedCultures and SupportedUICultures differ, and when should the two lists hold different cultures?

level: middleimportance: should knowfreq 40%
basics
~10 s

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

open as a page

In ASP.NET Core 10, what does WebApplicationFactory<Program> do when a test calls CreateClient, and what must the projects provide?

level: juniorimportance: must knowfreq 74%
basics
~20 s

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

open as a page

With Bogus, how do you build a Faker<Patient> that generates realistic patient records for an ASP.NET Core clinic-scheduling test suite?

level: juniorimportance: must knowfreq 48%
basics
~10 s

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

open as a page

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?

level: juniorimportance: must knowfreq 72%
basics
~20 s

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

open as a page

How do you run ASP.NET Core integration tests for an order-management API against a real PostgreSQL started with Testcontainers?

level: middleimportance: must knowfreq 55%
basics
~10 s

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

open as a page

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?

level: middleimportance: must knowfreq 66%
basics
~10 s

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

open as a page

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?

level: juniorimportance: must knowfreq 48%
basics
~20 s

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

open as a page

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?

level: juniorimportance: must knowfreq 55%
basics
~20 s

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

open as a page

In an ASP.NET Core 10 endpoint, why is calling .Result or .Wait() on a Task harmful, and what should you write instead?

level: juniorimportance: must knowfreq 72%
basics
~20 s

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

open as a page

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?

level: middleimportance: must knowfreq 45%
basics
~20 s

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

open as a page

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?

level: seniorimportance: must knowfreq 42%
basics
~20 s

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

open as a page

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?

level: juniorimportance: must knowfreq 62%
basics
~20 s

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

open as a page

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?

level: middleimportance: must knowfreq 45%
basics
~20 s

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

open as a page

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?

level: middleimportance: must knowfreq 50%
basics
~20 s

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

open as a page

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?

level: seniorimportance: must knowfreq 40%
basics
~20 s

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

open as a page

In an ASP.NET Core solution, how do ProjectReference items enforce clean-architecture dependency direction, and where can that enforcement still leak?

level: middleimportance: should knowfreq 38%
basics
~20 s

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

open as a page