📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š .NET Interview Questions

1325 questions for senior .NET engineer interviews, each with a 30-second answer, the full answer, a deep dive, the follow-ups interviewers ask next, and real-world production problems.

Phase 9 — ASP.NET Core

How ASP.NET Core on .NET 10 hosts, routes and handles requests: Kestrel and hosting, the middleware pipeline, Minimal APIs and MVC, configuration and options, logging, OpenAPI, and real-time and background services.

  1. Code review: a controller action wraps everything in try/catch and returns 200 with { success: false, error: ex.Message }, binds an EF Core entity directly from the request body and saves it, and validates fields by hand with if statements. What problems do you find, ranked by severity, and how would you rewrite it?

    Code review of a typical problematic controller: catch-all returning 200 with exception messages (information disclosure, broken HTTP semantics, swallowed errors), over-posting by binding EF entities, mass assignment of sensitive fields, hand-rolled validation, sync-over-async and missing cancellation, and a rewrite with request DTOs, validation, ProblemDetails, proper status codes and global exception handling.

    Senior CodeReview Request Handling Β· πŸ”— 2 follow-ups Β· πŸ›  1 real-world
  2. Your team has secrets and environment-specific settings scattered across appsettings.json files and portal app settings. How would you move them into Azure Key Vault and Azure App Configuration using managed identity, and how do you handle secret rotation, caching and refresh, start-up failures and feature flags?

    A real-world migration of ASP.NET Core configuration to Azure Key Vault and Azure App Configuration with managed identity: inventory and classification, RBAC roles, AddAzureKeyVault versus App Configuration Key Vault references, labels per environment, sentinel-key refresh and Key Vault reload intervals, rotation with overlapping secret versions, passwordless Entra ID auth, start-up resilience and replicas, feature flags with Microsoft.FeatureManagement, and the rollout plan.

    Senior RealWorldScenario Configuration Β· πŸ”— 2 follow-ups Β· πŸ›  1 real-world
  3. How does configuration work in ASP.NET Core? Explain the default configuration providers and the order they load in (appsettings.json, appsettings.{Environment}.json, user secrets, environment variables, command line), why the last one wins, and how hierarchical keys work with : and __.

    The ASP.NET Core configuration system: IConfiguration as a merged key-value view over ordered providers, the default sources added by WebApplication.CreateBuilder, last-provider-wins precedence, case-insensitive hierarchical keys with colon, double underscore for environment variables, array indexes and reading values with GetValue, GetSection and GetConnectionString.

    Beginner Theory Configuration Β· πŸ”— 2 follow-ups
  4. How do environments work in ASP.NET Core? Explain ASPNETCORE_ENVIRONMENT versus DOTNET_ENVIRONMENT, what IsDevelopment() changes, how environment-specific appsettings files are picked, and what should never go in appsettings.json.

    ASP.NET Core environments: how the environment name is resolved (ASPNETCORE_ENVIRONMENT, DOTNET_ENVIRONMENT, --environment, default Production), IHostEnvironment and IsDevelopment/IsProduction/IsEnvironment, what changes in Development (developer exception page, user secrets, DI validation), appsettings.{Environment}.json selection, launchSettings.json, and what belongs outside appsettings.

    Junior Theory Configuration Β· πŸ”— 2 follow-ups
  5. What are user secrets in .NET? Explain where they are stored, how they get loaded, why they are only for development, why they are not encryption, and what you use instead in production.

    The .NET Secret Manager: UserSecretsId in the project file, dotnet user-secrets init/set/list, the secrets.json location on Windows, Linux and macOS, loading only in the Development environment, why it is plain text outside the repo rather than encryption, and production replacements such as Azure Key Vault with managed identity and platform secret stores.

    Junior Theory Configuration Β· πŸ”— 2 follow-ups
  6. What is the options pattern in ASP.NET Core? Show how you bind a configuration section to a class with Configure<T> or AddOptions<T>().BindConfiguration(), explain how the binder maps keys to properties, and tell me why you shouldn't inject IConfiguration everywhere.

    The options pattern: binding configuration sections to strongly typed classes with Configure<T>, AddOptions<T>().Bind/BindConfiguration, how ConfigurationBinder maps keys to properties (case-insensitive, conversions, collections, missing keys, ErrorOnUnknownConfiguration), IConfigureOptions and PostConfigure for code-based setup, the binding source generator for AOT, and why injecting IConfiguration into services is an anti-pattern.

    Intermediate Theory Configuration Β· πŸ”— 2 follow-ups
  7. What is the difference between IOptions<T>, IOptionsSnapshot<T> and IOptionsMonitor<T>? Explain their lifetimes, how and when each sees configuration changes, how named options work, and which one you would use in a singleton, a controller and a background service.

    IOptions, IOptionsSnapshot and IOptionsMonitor compared: singleton, scoped and singleton lifetimes, computed once versus per scope versus cached and rebuilt on change tokens, CurrentValue and OnChange, named options with Get(name), the captive-dependency error, the per-request rebinding cost of IOptionsSnapshot, and how to choose for singletons, request handlers and BackgroundService.

    Mid-Level Theory Configuration Β· πŸ”— 2 follow-ups Β· πŸ›  1 real-world
  8. Show me how you validate options in ASP.NET Core so the app fails fast on bad configuration. Cover DataAnnotations with ValidateDataAnnotations, ValidateOnStart, custom rules with Validate and IValidateOptions<T>, nested objects, and the source-generated [OptionsValidator].

    Options validation in ASP.NET Core: ValidateDataAnnotations and its reflection cost, Validate delegates, IValidateOptions<T> for cross-property and service-dependent rules, ValidateOnStart to fail at host start-up, ValidateObjectMembers and ValidateEnumeratedItems for nested types, the compile-time [OptionsValidator] source generator for AOT, OptionsValidationException behaviour on reload, and testing validators.

    Mid-Level Coding Configuration Β· πŸ”— 2 follow-ups Β· πŸ›  1 real-world
  9. You set a configuration value in Azure App Service (or a Kubernetes deployment), but the running app still uses the value from appsettings.json. Possible causes include environment variable naming, provider precedence and reloadOnChange with mounted files. How do you diagnose and fix it?

    Diagnosing configuration values that don't take effect in Azure App Service, Container Apps or Kubernetes: environment variable naming (: versus __, ConfigMap key rules, App Service connection string prefixes), provider order and custom sources added last, the wrong environment name, values read once at start-up, mounted ConfigMap symlink swaps and DOTNET_USE_POLLING_FILE_WATCHER, and using GetDebugView with masking, the provider list, printenv and az CLI to find which provider won.

    Mid-Level Debugging Configuration Β· πŸ”— 2 follow-ups Β· πŸ›  1 real-world
  10. Code review: a start-up class stores builder.Configuration in a static AppConfig.Config property, services read keys from it in their constructors (one parses a port with int.Parse and opens a SQL connection), and appsettings.json, committed to git, contains an SMTP password and a live Stripe secret key. What do you find, ranked by severity, and how would you rewrite it?

    Code review of configuration anti-patterns: secrets committed in appsettings.json (incident response, rotation, history, Privacy Act and NDB), constructors that parse configuration and open connections, a static IConfiguration singleton (hidden dependencies, test pollution, no reload), no validation, and the rewrite with options classes, ValidateOnStart, Key Vault with managed identity and passwordless SQL, plus blocking versus suggested review comments and secret scanning.

    Senior CodeReview Configuration Β· πŸ”— 2 follow-ups Β· πŸ›  1 real-world
  11. What is ILogger<T> in ASP.NET Core? Explain the log levels, what a log category is, and how you filter logs per category in appsettings.json.

    ILogger<T> basics: the six log levels plus None, categories derived from the type name, the Logging:LogLevel section in appsettings.json, per-provider overrides, most-specific-prefix matching and the default levels in the ASP.NET Core templates.

    Beginner Theory Logging Β· πŸ”— 3 follow-ups
  12. What logging providers come with .NET (console, debug, EventSource, EventLog) and which ones do you add for Application Insights and OpenTelemetry? How does ILoggerFactory send one log call to several providers, and how do you choose and configure them?

    Logging providers in Microsoft.Extensions.Logging: the defaults added by WebApplication.CreateBuilder (Console, Debug, EventSource, EventLog on Windows), adding OpenTelemetry or Azure Monitor, ClearProviders, how ILoggerFactory fans a call out to one ILogger per provider with per-provider filtering, console formatters and the cost of synchronous providers.

    Junior Theory Logging Β· πŸ”— 3 follow-ups
  13. What is structured logging? Explain message templates versus string interpolation (and the CA2254 warning), how named placeholders become properties, and why this matters when you query logs in Application Insights or Seq.

    Structured logging in .NET: message templates with named placeholders, how LogValues keeps the template and arguments separately, why $"..." interpolation destroys properties and allocates even when filtered (CA2254), the @ and $ destructuring hints in Serilog, KQL queries over customDimensions, cardinality and naming conventions.

    Intermediate Theory Logging Β· πŸ”— 3 follow-ups
  14. Show me how you write high-performance logging in .NET. Use the [LoggerMessage] source generator, explain what it does differently from logger.LogInformation(...) with arguments, when IsEnabled checks still matter, and how you would prove the difference with a benchmark.

    High-performance logging: the cost of LoggerExtensions calls (params object[] allocation, boxing, template parsing), the [LoggerMessage] source generator on partial methods, generated IsEnabled checks and cached delegates, CA1848, guarding expensive arguments with IsEnabled, and a BenchmarkDotNet comparison with MemoryDiagnoser.

    Mid-Level Coding Logging Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  15. Serilog, NLog, or the built-in Microsoft.Extensions.Logging with OpenTelemetry: how does each plug into ASP.NET Core, what are sinks, targets and enrichers, and how would you choose for a new .NET 10 service today?

    Comparing logging stacks for ASP.NET Core on .NET 10: Serilog (AddSerilog, two-stage bootstrap, sinks, enrichers, Serilog.Settings.Configuration), NLog (UseNLog, targets, layouts, nlog.config), and the built-in abstraction with OpenTelemetry exporters; how each sits behind ILogger, what OpenTelemetry changes, and a decision guide.

    Intermediate Theory Logging Β· πŸ”— 2 follow-ups
  16. How do you correlate all the logs for one request across services? Explain log scopes with BeginScope, how Activity and the W3C traceparent header give you a trace id, how that id propagates to HttpClient calls and message queues, and whether you still need a custom correlation ID.

    Log scopes and correlation in ASP.NET Core: ILogger.BeginScope and scope providers, the hosting scope (RequestId, RequestPath), ActivityTrackingOptions adding TraceId and SpanId, System.Diagnostics.Activity and AsyncLocal flow, W3C Trace Context (traceparent, tracestate, baggage), automatic propagation through HttpClient, propagating through Azure Service Bus messages, and when a business correlation ID is still useful.

    Mid-Level Theory Logging Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  17. How do you set up OpenTelemetry in an ASP.NET Core service? Explain how logs, traces and metrics fit together, what the OTLP exporter and the Azure Monitor distro each do, and how you approach sampling so you keep the useful data without an enormous bill.

    OpenTelemetry in ASP.NET Core on .NET 10: the three signals and how logs carry TraceId/SpanId, AddOpenTelemetry with WithTracing, WithMetrics and WithLogging, resource attributes, built-in ASP.NET Core and HttpClient instrumentation and meters, UseOtlpExporter vs the Azure Monitor distro (UseAzureMonitor, rate-limited sampling default since 1.5), head versus tail sampling in the Collector, and cost control.

    Senior Theory Logging Β· πŸ”— 2 follow-ups Β· πŸ›  1 real-world
  18. How do you keep personal information and secrets out of your logs in an ASP.NET Core service? Cover what must never be logged, data classification and redaction with Microsoft.Extensions.Compliance.Redaction, HTTP logging, and what the Privacy Act (APP 11) means for log retention and breaches.

    Secure logging: what counts as secrets and personal information, why logs are a breach surface, Microsoft.Extensions.Compliance.Redaction (data classification attributes, AddRedaction, EnableRedaction, erasing and HMAC redactors, [LogProperties]), safe HTTP logging and header allowlists, scanning and testing for leaks, and Australian Privacy Act APP 11, APP 11.2 retention and the Notifiable Data Breaches scheme.

    Senior Security Logging Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  19. Your Application Insights bill has tripled in a month and API latency has risen, and both trace back to logging. How do you find exactly what is producing the volume, fix log levels, sampling and sinks, and keep costs under control without losing the data you need for incidents?

    A real-world logging cost and latency incident: finding ingestion sources with KQL over _BilledSize by table, category and template, common causes (Debug left on, EF Core command logging, HTTP body logging, duplicate pipelines, health-check noise, disabled sampling), latency from synchronous or blocked log writes, fixes in levels, filters, sampling and sinks, and long-term controls such as daily caps, table plans, transformations and cost alerts.

    Senior RealWorldScenario Logging Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  20. Your OpenAPI document is wrong: some endpoints are missing, responses have no schema, polymorphic types show only the base class, enums appear as integers and nullability is wrong. How do you diagnose and fix it?

    Debugging question on a wrong or incomplete OpenAPI document in ASP.NET Core: endpoints missing from API Explorer, untyped IResult responses, JsonPolymorphic and JsonDerivedType for oneOf, enum converters, nullable and required properties, and a snapshot test to keep it right.

    Mid-Level Debugging API Features Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me