Advertisement

Information Technology

ASP.NET Core Interview Questions & Answers

Build modern web apps and APIs.

20topics 300questions last updated
Advertisement

API Documentation with Swagger/OpenAPI

All 15 questions
  1. OpenAPI is a language-agnostic specification format for describing REST API contracts (endpoints, parameters, request/response schemas, authentication) in JSON or YAML. Swashbuckle…

  2. Enabling GenerateDocumentationFile in the .csproj causes the compiler to extract /// XML doc comments into a .xml file, which Swashbuckle can be configured to read via IncludeXmlCo…

  3. Configure AddSecurityDefinition to describe the authentication scheme (e.g., Bearer JWT) and AddSecurityRequirement to apply it globally or per-operation, which adds an 'Authorize'…

  4. The [ProducesResponseType(typeof(T), StatusCode)] attribute (or its minimal API equivalent, .Produces (statusCode)) explicitly declares each possible response shape and status code…

  5. Microsoft.AspNetCore.OpenApi is a first-party, built-in package for generating OpenAPI documents, designed for better performance (using source generators and reduced reflection ov…

API Versioning

All 15 questions
  1. Without explicit versioning, any change to an endpoint's contract risks breaking existing consumers who can't control when they upgrade -- the Asp.Versioning.Mvc (for controllers)…

  2. Apply [ApiVersion("1.0")] to a controller and include {version:apiVersion} in its route template; the versioning middleware then matches incoming requests' URL version segment to t…

  3. Asp.Versioning.Http provides a NewVersionedApi() builder extension and .HasApiVersion()/.MapToApiVersion() methods for grouping and versioning minimal API endpoint groups, mirrorin…

  4. Header-based versioning reads the version from a custom request header (like X-Api-Version) rather than the URL path, configured via options.ApiVersionReader = new HeaderApiVersion…

  5. Marking a version with [ApiVersion("1.0", Deprecated = true)] combined with options.ReportApiVersions = true causes the middleware to automatically include api-deprecated-versions…

Authentication

All 15 questions
  1. Authentication is the process of establishing a user's identity, resulting in a ClaimsPrincipal (accessible via HttpContext.User) populated with claims describing that user -- name…

  2. Cookie authentication issues an encrypted, signed cookie after successful login (via SignInAsync), which the browser automatically attaches to subsequent same-site requests; the se…

  3. The JWT bearer handler extracts the token from the Authorization: Bearer header, verifies its cryptographic signature against the configured signing key, and validates standard cla…

  4. Register multiple named schemes via chained AddCookie/AddJwtBearer calls, then specify which scheme(s) apply per endpoint using [Authorize(AuthenticationSchemes = "Bearer")] on API…

  5. Dedicated handler packages (Microsoft.AspNetCore.Authentication.Google, .MicrosoftAccount, or the generic OpenID Connect handler for any OIDC-compliant provider) implement the OAut…

Authorization

All 15 questions
  1. Role-based authorization ([Authorize(Roles = "Admin")]) checks whether the user's ClaimsPrincipal has a role claim matching one of the specified roles -- a simple, coarse-grained c…

  2. AddAuthorization registers named policies built from one or more IAuthorizationRequirement objects (or simple RequireClaim/RequireRole/RequireAssertion builder calls for straightfo…

  3. Resource-based authorization uses IAuthorizationService.AuthorizeAsync(user, resource, requirement) directly within your action/endpoint (rather than a declarative attribute, since…

  4. A 401 Unauthorized response means the request lacks valid authentication credentials entirely (or they failed to validate) -- the user isn't recognized at all. A 403 Forbidden mean…

  5. Define a class implementing IAuthorizationRequirement (often just a marker with no logic itself), then an AuthorizationHandler subclass implementing HandleRequirementAsync that eva…

Background Tasks & Hosted Services

All 15 questions
  1. BackgroundService is an abstract base class for long-running background work that runs within the same process as your web application, started automatically at application startup…

  2. Since a BackgroundService instance is a singleton for the application's lifetime, you can't inject scoped services (like AppDbContext) directly into its constructor -- inject IServ…

  3. When the host begins shutting down, it signals the CancellationToken passed to ExecuteAsync and gives the service a configurable grace period (ShutdownTimeout, default 30 seconds)…

  4. An unhandled exception escaping ExecuteAsync stops the BackgroundService entirely (and depending on configuration, can bring down the whole host), so production code should wrap in…

  5. Channel provides a high-performance, thread-safe async queue -- a producer (like an API endpoint) writes items via ChannelWriter.WriteAsync, while a BackgroundService acts as the c…

Blazor Integration with ASP.NET Core

All 15 questions
  1. Blazor runs on top of the same ASP.NET Core hosting infrastructure (Kestrel, middleware pipeline, DI container) as any other ASP.NET Core app. Interactive Server mode executes comp…

  2. Since .NET 8's unified hosting model, a single ASP.NET Core project can register both MapControllers()/MapRazorPages() and MapRazorComponents () in the same Program.cs, letting tra…

  3. Both consume the exact same IServiceCollection registrations from Program.cs -- a service registered once via AddScoped/AddSingleton/AddTransient is resolvable both in an MVC contr…

  4. AuthenticationStateProvider is the abstraction Blazor components use (via the component or @attribute [Authorize]) to access the current user's authentication state -- for Blazor S…

  5. Since a Blazor Server circuit maintains persistent server-side state tied to one specific server instance via its SignalR connection, load balancers must be configured for sticky s…

  1. IMemoryCache is a built-in in-process cache storing key-value pairs directly in the application's own memory, extremely fast since it requires no network round-trip, but not shared…

  2. IDistributedCache is an abstraction over an external, shared cache store (commonly Redis) that all instances of a scaled-out application read from and write to consistently, ensuri…

  3. Response caching (via UseResponseCaching() and [ResponseCache] attributes) caches entire HTTP responses at the HTTP layer based on cache-control headers, serving cached output dire…

  4. Output Caching (UseOutputCache(), CacheOutput() policies) caches the response server-side (unlike Response Caching, which relies on client/proxy cache-control headers and doesn't a…

  5. A cache stampede occurs when a popular cache entry expires and many concurrent requests simultaneously experience a cache miss, all racing to recompute and repopulate the same expe…

Configuration & Options Pattern

All 15 questions
  1. IConfiguration builds a unified key-value tree by combining multiple providers in registration order, where later-registered providers override earlier ones for the same key -- the…

  2. The Options pattern binds a strongly-typed C# class to a section of configuration (via IOptions /IOptionsSnapshot /IOptionsMonitor ), giving compile-time type safety, IntelliSense,…

  3. IOptions is registered as a singleton, computed once at first access and never refreshed even if configuration changes at runtime -- safe for singletons, suitable for genuinely sta…

  4. ASP.NET Core loads appsettings.json first as a base configuration, then layers appsettings.{EnvironmentName}.json on top, overriding matching keys, with the environment determined…

  5. Chaining .ValidateDataAnnotations().ValidateOnStart() on the options builder ensures configuration is validated immediately when the application starts (rather than lazily on first…

Content Negotiation & Output Formatters

All 15 questions
  1. Content negotiation is the process by which the server determines the format (JSON, XML, plain text) to return a response in, based on the client's Accept header expressing its pre…

  2. AddXmlSerializerFormatters() (or AddXmlDataContractSerializerFormatters() for an alternative serialization approach) registers XML input/output formatters alongside the default JSO…

  3. Subclass TextOutputFormatter (or OutputFormatter for binary formats), override CanWriteType to declare which types it supports, set SupportedMediaTypes to the custom MIME type (lik…

  4. The framework parses the Accept header's comma-separated list of media types, each optionally annotated with a q-value (like application/json;q=0.9,application/xml;q=0.5) indicatin…

  5. Browsers typically send an Accept header requesting HTML first (text/html) since that's their primary use case for regular web browsing, even when a developer manually navigates to…

Controllers vs Minimal APIs

All 15 questions
  1. Controller-based APIs organize endpoints as methods within controller classes (inheriting ControllerBase), using attributes ([HttpGet], [Route]) to define routes, relying on the MV…

  2. Controllers provide built-in support for action filters/exception filters/result filters (a rich, multi-stage filter pipeline), automatic model validation via [ApiController]'s Mod…

  3. Minimal APIs generally have lower per-request overhead since they bypass much of the MVC framework's action invocation machinery (the filter pipeline resolution, model binding via…

  4. Common patterns include extension methods grouping related endpoint registrations (e.g., MapProductEndpoints(this WebApplication app)) called once from Program.cs, or the newer Rou…

  5. Consider: team familiarity (existing MVC expertise favors controllers, reducing onboarding friction), project complexity (many cross-cutting concerns like complex filters, view ren…

CORS (Cross-Origin Resource Sharing)

All 15 questions
  1. CORS is a browser-enforced security mechanism restricting web pages from making requests to a different origin (scheme, domain, or port) than the one that served the page, unless t…

  2. UseCors must come after UseRouting (since it may need endpoint-specific policy metadata from routing) but before UseAuthorization (since a CORS preflight OPTIONS request carries no…

  3. For 'non-simple' requests (using methods other than GET/HEAD/POST, custom headers, or a Content-Type outside a few basic ones like application/x-www-form-urlencoded), the browser s…

  4. The CORS specification explicitly forbids combining AllowCredentials (needed for cookie-based auth or client certificates across origins) with a wildcard origin, as a security meas…

  5. Register multiple named policies via AddCors, then apply a specific one per controller/action using [EnableCors("PolicyName")] (overriding any default/global policy), or per minima…

Dependency Injection

All 15 questions
  1. Dependency injection is a design pattern where a class receives its dependencies from an external source rather than creating them itself, promoting loose coupling and testability.…

  2. Singleton creates one instance for the entire application lifetime, shared across all requests. Scoped creates one instance per client HTTP request (a new DI scope is created at th…

  3. A captive dependency occurs when a longer-lived service (Singleton) depends on a shorter-lived service (Scoped), effectively 'capturing' that shorter-lived instance for the Singlet…

  4. Calling AddScoped/AddSingleton/AddTransient multiple times for the same interface with different implementations registers all of them; injecting IEnumerable resolves the full coll…

  5. Keyed services let you register multiple implementations of the same interface under distinct string or object keys, resolved explicitly via [FromKeyedServices("key")] or GetRequir…

Endpoint Metadata, Route Constraints & Templates

All 15 questions
  1. A route template defines the URL pattern an endpoint matches, with curly-brace segments ({id}) representing route parameters extracted from the actual request URL and made availabl…

  2. Route constraints, appended after a colon in the route parameter syntax, restrict matching to values satisfying a specific type or pattern -- {id:int} only matches numeric segments…

  3. Implement IRouteConstraint's Match method containing the custom matching logic (like a regex check against a specific SKU pattern), register it with a name in the RouteOptions.Cons…

  4. Endpoint metadata is arbitrary data attached to a matched route (via attributes on controller actions, or .WithMetadata()/.RequireAuthorization() fluent calls on minimal API endpoi…

  5. Custom middleware calls context.GetEndpoint()?.Metadata.GetMetadata () to check for a specific metadata type attached to the matched endpoint, letting one piece of middleware behav…

Error Handling

All 15 questions
  1. Global exception handling middleware catches unhandled exceptions thrown anywhere downstream in the pipeline, preventing them from crashing the request or leaking a raw stack trace…

  2. IExceptionHandler defines TryHandleAsync(HttpContext, Exception, CancellationToken), implemented as a proper, testable, DI-injectable class -- multiple exception handlers can be re…

  3. ProblemDetails is a standardized JSON format for HTTP API error responses, including fields like type, title, status, detail, and instance, providing a consistent, interoperable er…

  4. Inside your exception handler, inspect the caught exception's type (or a custom base exception hierarchy) and map it to the semantically correct HTTP status code -- a NotFoundExcep…

  5. Production error responses should never include raw exception messages, stack traces, internal file paths, database connection details, or anything revealing internal architecture,…

File Uploads & Streaming Large Files

All 15 questions
  1. An action parameter of type IFormFile automatically binds an uploaded file from a multipart/form-data request, giving access to its stream (OpenReadStream()), file name, content ty…

  2. IFormFile by default buffers the entire uploaded file (potentially to memory or a temp disk file depending on size) before your action code even runs, which for very large files (v…

  3. Disable the default form value model binding (via [DisableFormValueModelBinding] and not using an IFormFile parameter at all), then manually read the multipart request using Multip…

  4. Kestrel's default MaxRequestBodySize is 30MB; configure it via KestrelServerOptions.Limits.MaxRequestBodySize globally, or override per-endpoint via [RequestSizeLimit(bytes)] on a…

  5. A chunked upload protocol splits a large file into smaller pieces uploaded via separate requests (each with a chunk index and total chunk count), with the server accumulating chunk…

  1. Filters let you run code at specific stages surrounding an MVC action's execution: Authorization filters run first (checking access before anything else), Resource filters wrap the…

  2. Global filters are registered via options.Filters.Add() in AddControllers(), applying to every action in the application. Controller-scoped filters are applied as an attribute dire…

  3. IAsyncActionFilter's single OnActionExecutionAsync method receives an ActionExecutionDelegate you explicitly await to continue the pipeline (giving you a single, clear place for bo…

  4. [TypeFilter(typeof(MyFilter), Arguments = new object[] { "someValue" })] instantiates the filter via the DI container but lets you pass additional constructor arguments not resolva…

  5. Exception filters run within the MVC action invocation pipeline specifically, giving access to MVC-specific context (like the ActionDescriptor and ModelState) that middleware-level…

gRPC Services

All 15 questions
  1. gRPC is a high-performance RPC (Remote Procedure Call) framework built on HTTP/2 that uses Protocol Buffers (protobuf) for compact binary serialization and strongly-typed service c…

  2. A .proto file defines the service's RPC methods and message types using protobuf syntax; the Grpc.Tools NuGet package's build-time code generation (via in the .csproj) automaticall…

  3. Unary (single request, single response) is the default and covers most simple RPC calls, analogous to a typical REST call. Server streaming (single request, stream of responses) su…

  4. Standard gRPC requires full HTTP/2 features (particularly trailers, sent after the response body, used to carry the final status) that browser JavaScript fetch/XHR APIs don't expos…

  5. gRPC authentication commonly uses JWT bearer tokens passed via a custom metadata header (equivalent to an HTTP header) on each call, validated through the same JWT bearer authentic…

Health Checks

All 15 questions
  1. The Health Checks middleware (Microsoft.AspNetCore.Diagnostics.HealthChecks) provides a standardized way for an application to report its own operational health status, exposed via…

  2. Implement IHealthCheck's single CheckHealthAsync method, returning HealthCheckResult.Healthy(), .Degraded(), or .Unhealthy() (each optionally with a description and data dictionary…

  3. Liveness checks answer 'is the process alive and not deadlocked' (a failure means the container should be restarted), while readiness checks answer 'is this instance ready to recei…

  4. The default MapHealthChecks() endpoint returns only plain text ("Healthy", "Unhealthy"), but you can supply a custom ResponseWriter delegate in HealthCheckOptions to produce a stru…

  5. Measure the relevant metric (e.g., time a test query takes) inside CheckHealthAsync and compare it against defined thresholds, returning HealthCheckResult.Healthy() below a normal…

Hosting Models: Kestrel, IIS & Reverse Proxies

All 15 questions
  1. Kestrel is the default, cross-platform, high-performance web server built directly into ASP.NET Core, responsible for handling raw HTTP connections and requests -- unlike IIS (a fu…

  2. In-process hosting runs the ASP.NET Core application directly inside the IIS worker process (w3wp.exe) via the AspNetCoreModuleV2, avoiding an extra network hop and providing bette…

  3. Running Kestrel directly exposed to the internet requires manually configuring what a reverse proxy would otherwise provide: request size limits, connection/request timeouts, minim…

  4. Behind a reverse proxy, HttpContext.Connection.RemoteIpAddress and Request.Scheme by default reflect the proxy's own connection details, not the original client's -- the ForwardedH…

  5. YARP is Microsoft's own open-source, code-first reverse proxy toolkit built on ASP.NET Core itself, letting you build a fully customizable reverse proxy/API gateway in C# (with rou…

HTTPS, Certificates & Transport Security

All 15 questions
  1. The UseHttpsRedirection() middleware, registered early in the pipeline, automatically issues a redirect (307 by default) to the HTTPS equivalent of any incoming HTTP request's URL…

  2. HSTS is a response header (Strict-Transport-Security) instructing browsers to automatically convert any future request to the site into HTTPS internally, without even attempting a…

  3. Kestrel's HTTPS configuration accepts a certificate via several sources: a PFX file with a password (common for development/simple deployments), the Windows/Linux certificate store…

  4. A self-signed certificate is one not issued by a trusted Certificate Authority (CA), meaning browsers and other clients don't inherently trust it and will show security warnings un…

  5. Mutual TLS requires configuring Kestrel to request and validate a client certificate during the TLS handshake (ClientCertificateMode.RequireCertificate), then using the Certificate…