Ultimate ASP.NET Core Interview Guide 2026: 200+ AI & Cloud Q&A for All Levels (Beginner to Architect) | FreeLearning365

Ultimate ASP.NET Core Interview Guide 2026: 220+ AI & Cloud Q&A for All Levels (Beginner to Architect)
🔥 Ace Your Next Interview

3000+ real questions, mock interviews & AI‑powered feedback – all in one portal.

🚀 Go to Job Interview Portal

Ultimate ASP.NET Core Interview Guide 2026

220+ Q&A with business scenarios, AI integration & hands‑on code – from Beginner to Architect

🔰 Beginner Level (0‑2 years experience) – 60 Questions

1. What is ASP.NET Core and how does it differ from classic ASP.NET?

ASP.NET Core is a cross‑platform, high‑performance, open‑source framework for building modern cloud‑based applications. Unlike classic ASP.NET (which ran only on Windows/IIS), Core runs on Windows, Linux, and macOS. It's modular, uses a built‑in DI container, and completely eliminates System.Web. The unified programming model merges MVC, Web API, and Razor Pages into one pipeline.

2. Explain the Startup class. How has it changed in .NET 6+?

Traditionally, Startup has ConfigureServices and Configure. In .NET 6+ minimal hosting model, top‑level statements replace it, but services and middleware are configured directly on WebApplicationBuilder and WebApplication. Under the hood the same concepts apply.

3. What is Dependency Injection and how do you register services?

ASP.NET Core has a built‑in IoC container. Register services in Program.cs with lifetimes: Transient (new every time), Scoped (per request), Singleton (once). Example: builder.Services.AddScoped<IProductRepository, ProductRepository>();

4. Write a simple middleware that logs every request’s path and duration.
app.Use(async (context, next) => {
    var start = DateTime.UtcNow;
    Console.WriteLine($"Request: {context.Request.Path}");
    await next();
    Console.WriteLine($"Duration: {(DateTime.UtcNow - start).TotalMilliseconds}ms");
});
5. What is the difference between app.Run, app.Use, and app.Map?

Run is a terminal middleware that doesn't call next. Use can call the next delegate. Map branches the pipeline based on request path.

6. How does configuration work? Show how to read from appsettings.json.

Use IConfiguration injected via constructor. Example: var conn = _configuration.GetConnectionString("Default");. The file is loaded by default in CreateBuilder.

7. What are the built‑in logging providers in ASP.NET Core?

Console, Debug, EventSource, EventLog (Windows), and third‑party via Serilog, NLog. Configure logging with builder.Logging.AddConsole().

8. Create a minimal API endpoint that returns “Hello World”.
var app = WebApplication.Create(args);
app.MapGet("/", () => "Hello World!");
app.Run();
9. What is routing in ASP.NET Core? Explain attribute routing.

Routing matches incoming HTTP requests to endpoints. Attribute routing uses [Route], [HttpGet] attributes on controllers/actions. Example: [HttpGet("api/products/{id}")].

10. How does model binding work? Give an example with a complex type.

The framework binds incoming form data, query string, route data to action parameters. For a Product class, public IActionResult Create([FromBody] Product p) binds from JSON body automatically.

11. What is the purpose of appsettings.{Environment}.json?

It overrides settings based on the current environment (Development, Staging, Production). ASP.NET Core merges them automatically.

12. How do you enable CORS in an ASP.NET Core API?
builder.Services.AddCors(o => o.AddPolicy("AllowAll", p => p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));
app.UseCors("AllowAll");
13. Explain the difference between IActionResult and ActionResult<T>.

IActionResult can return any HTTP response. ActionResult<T> is a union type that allows returning either a T instance (which becomes Ok) or an ActionResult (like NotFound).

14. What is Entity Framework Core? Show a simple DbContext.
public class AppDbContext : DbContext {
    public DbSet<Product> Products { get; set; }
    public AppDbContext(DbContextOptions<AppDbContext> o) : base(o) {}
}
15. How do you apply database migrations in EF Core?

Use CLI: dotnet ef migrations add Initial then dotnet ef database update. Or programmatically: context.Database.Migrate().

16. What is a Razor Page? When would you use it over MVC?

Razor Pages are page‑focused, suitable for simple page‑based apps. They use a PageModel class and are less ceremony than MVC for CRUD UIs.

17. How do you handle errors globally in ASP.NET Core?

Use the exception handler middleware: app.UseExceptionHandler("/Home/Error") or app.UseDeveloperExceptionPage() in development.

18. What is a Tag Helper? Give an example.

Tag Helpers enable server‑side code to create and render HTML elements. Example: <label asp-for="Email"></label> generates proper labels with validation attributes.

19. Explain the HostBuilder and how to configure Kestrel.

Use builder.WebHost.ConfigureKestrel(options => options.Listen(IPAddress.Any, 5000)); to bind to a specific port.

20. What are environments (Development, Staging, Production) and how do you set them?

Set via ASPNETCORE_ENVIRONMENT environment variable. The app reads it with IWebHostEnvironment and can load environment‑specific settings.

21. How do you serve static files?

Add app.UseStaticFiles() and place files in wwwroot folder. You can configure cache duration: app.UseStaticFiles(new StaticFileOptions { ... }).

22. What is the difference between AddControllers, AddControllersWithViews, and AddRazorPages?

AddControllers is for API controllers only, no views. AddControllersWithViews includes view support. AddRazorPages adds Razor Pages services.

23. How do you implement JSON serialization options globally?

Use builder.Services.AddControllers().AddJsonOptions(opt => opt.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase);

24. What is the purpose of the launchSettings.json file?

It stores profiles for IIS Express or Kestrel, environment variables, and URLs used during development. Not published.

25. Write a simple health check endpoint.
builder.Services.AddHealthChecks();
app.MapHealthChecks("/health");
26. How do you validate a model using Data Annotations?

Decorate properties with [Required], [MaxLength(100)], etc. In controller check ModelState.IsValid.

27. What is the purpose of the IHttpClientFactory?

It manages HttpClient instances efficiently, avoiding socket exhaustion. Register via builder.Services.AddHttpClient().

28. Create a simple CRUD API for a product resource using EF Core.
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase {
    private readonly AppDbContext _db;
    public ProductsController(AppDbContext db) => _db = db;

    [HttpGet]
    public async Task<ActionResult> GetAll() => Ok(await _db.Products.ToListAsync());

    [HttpPost]
    public async Task<ActionResult> Create(Product p) {
        _db.Products.Add(p);
        await _db.SaveChangesAsync();
        return CreatedAtAction(nameof(GetAll), new { id = p.Id }, p);
    }
}
29. How do you read a query string parameter?

Use HttpContext.Request.Query["key"] or model binding in action parameter public IActionResult Search(string q).

30. What is the difference between TempData, ViewData, and ViewBag?

TempData persists across requests, ViewData is a dictionary for the current request, ViewBag is a dynamic wrapper around ViewData.

31. How do you enable session state in ASP.NET Core?

Add builder.Services.AddSession() and app.UseSession(), then use HttpContext.Session.SetString("key", "val").

32. What is the role of the IWebHostEnvironment interface?

Provides information about the web hosting environment, like EnvironmentName, ContentRootPath. Use it to conditionally configure services.

33. How can you return a custom status code from an action?

Return StatusCode(418) or return new ObjectResult("teapot") { StatusCode = 418 };.

34. Explain the concept of endpoint routing.

Endpoint routing decouples route matching from endpoint execution, allowing middlewares like authorization, CORS to know the final endpoint early.

35. How do you set the request timeout for Kestrel?

Use builder.WebHost.ConfigureKestrel(o => o.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2));

36. What are the benefits of using async/await in controllers?

Frees threads for other requests, improves scalability under high concurrency.

37. How do you configure multiple environments using appsettings?

Create appsettings.Development.json, appsettings.Production.json. The system merges them automatically.

38. Write a simple filter that logs action execution time.
public class TimerFilter : IActionFilter {
    public void OnActionExecuting(ActionExecutingContext context) {
        context.HttpContext.Items["Start"] = DateTime.UtcNow;
    }
    public void OnActionExecuted(ActionExecutedContext context) {
        var start = (DateTime)context.HttpContext.Items["Start"];
        Console.WriteLine($"Action took {(DateTime.UtcNow - start).TotalMilliseconds}ms");
    }
}
39. What is the difference between AddMvc, AddRazorPages, and AddControllers?

AddMvc includes views, API, Razor Pages. AddRazorPages only Razor Pages. AddControllers only API controllers. Prefer AddControllers/AddRazorPages for smaller footprint.

40. How do you secure an API with API keys?

Create a middleware that checks X-API-Key header and rejects if invalid. Register it early in the pipeline.

41. What is the purpose of the appsettings.json file?

Stores non‑secret configuration data like connection strings, logging levels, custom settings in a hierarchical format.

42. Explain the difference between WebApplication and generic IHost.

WebApplication is a specialized host for web apps, automatically configures Kestrel, routing, etc. IHost is for background services without web.

43. How do you add Swagger/OpenAPI to an ASP.NET Core project?

Install Swashbuckle. builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); and app.UseSwagger(); app.UseSwaggerUI();

44. What is the role of Program.cs in .NET 6+?

It replaces the old Main method and Startup. It creates the builder, configures services, builds the app, and configures middleware – all in one file.

45. How do you format JSON response in camelCase?

Default in ASP.NET Core 3+ uses camelCase. You can customize in AddJsonOptions.

46. What is a controller action? Explain the non‑overloaded action selection.

Actions are public methods in a controller. Routing selects based on method name, HTTP verb, and parameters.

47. How do you bind a complex object from form data?

Use [FromForm] attribute. The model binder matches form fields to properties.

48. What is the purpose of the ContentRootPath and WebRootPath?

ContentRootPath is the project root, WebRootPath is wwwroot for static files.

49. How do you disable automatic model state validation for API controllers?

Set options.SuppressModelStateInvalidFilter = true; in AddControllers.

50. Write a middleware that returns a custom 500 error page.
app.UseExceptionHandler(errorApp => {
    errorApp.Run(async context => {
        context.Response.StatusCode = 500;
        await context.Response.WriteAsync("Internal Server Error. Please try later.");
    });
});
51. What is the difference between app.Run() and app.Use() when defining the pipeline?

Run does not call next middleware; Use may call the next delegate.

52. How do you read a custom setting from a JSON config file?

_configuration.GetValue<string>("CustomSettings:Key") or using options pattern with services.Configure<T>().

53. What is a service lifetime? Describe transient, scoped, singleton.

Transient: new instance every injection. Scoped: same within a request. Singleton: one instance for app lifetime.

54. How can you register multiple implementations of an interface?

Register them individually, then inject IEnumerable<IMyInterface>. Or use a factory pattern.

55. What is the purpose of the IServiceProvider?

It’s the DI container root from which you can resolve any service manually.

56. How do you execute code after the app starts?

Use app.Lifetime.ApplicationStarted.Register(() => { ... }); or implement IHostedService.

57. What is the difference between a WebHost and a Generic Host?

Generic Host supports non‑web scenarios (background workers, etc.). ASP.NET Core uses it with web‑specific configuration.

58. How do you handle file uploads in an API?

Accept IFormFile parameter. Use using var stream = new FileStream(...); await file.CopyToAsync(stream);

59. What is a response compression middleware?

It compresses responses using gzip/brotli. Enable with builder.Services.AddResponseCompression() and app.UseResponseCompression().

60. How do you implement a simple in‑memory cache?

Inject IMemoryCache. Use _cache.Set("key", value, TimeSpan.FromMinutes(5));

🟡 Intermediate Level (2‑5 years) – 60 Questions

61. Design a high‑traffic product search API with caching and pagination.

Business need: 10k concurrent users. Use async, IMemoryCache/Redis, pagination via Skip/Take, DTO projections with AutoMapper, response compression, and ETag headers for caching validation.

62. How does ASP.NET Core model validation work with FluentValidation?

Install FluentValidation.AspNetCore. Register validators. Use AbstractValidator<T> and call services.AddFluentValidationAutoValidation().

63. Explain the pipeline of an HTTP request in ASP.NET Core.

Request → Kestrel → Hosting pipeline → middleware 1 → … → terminal middleware → response back through middleware → Kestrel.

64. How do you implement JWT authentication step by step?

Add AddAuthentication(JwtBearerDefaults.AuthenticationScheme), configure JwtBearer options with authority, audience. Generate token in a controller after validating credentials.

65. What is the difference between cookie auth and JWT?

Cookie: server‑side sessions, works well for MVC. JWT: stateless, suitable for APIs, can be used across domains.

66. How do you authorize based on policies?

Define policies with requirements: options.AddPolicy("AdminOnly", p => p.RequireRole("Admin")); Then [Authorize(Policy = "AdminOnly")].

67. Explain the Identity framework. How do you customise user properties?

Inherit from IdentityUser to add fields. services.AddIdentity<MyUser, IdentityRole>(). Use custom UserStore if needed.

68. How would you implement multi‑factor authentication in ASP.NET Core?

Enable MFA via Identity, generate a TOTP token, and validate with UserManager.GenerateTwoFactorTokenAsync and VerifyTwoFactorTokenAsync.

69. What is a DbContext pool and why use it?

Use AddDbContextPool<T>() to reuse context instances, improving performance for high‑throughput APIs.

70. How do you handle concurrency conflicts in EF Core?

Use a row version column ([Timestamp]) and catch DbUpdateConcurrencyException to resolve.

71. Design an API versioning strategy.

Use URL segment (/api/v1/products), query string, or header. Install Microsoft.AspNetCore.Mvc.Versioning, configure and annotate controllers.

72. How do you implement a custom model binder?

Implement IModelBinder and IModelBinderProvider, register in MvcOptions.

73. What is the role of ObjectPool<T> and how can you use it?

It reuses objects to reduce GC pressure. Can be used to pool StringBuilder instances via Microsoft.Extensions.ObjectPool.

74. How do you stream large files with ASP.NET Core without loading into memory?

Use FileStreamResult with FileStream and enable response buffering off. Or IAsyncEnumerable with System.Text.Json streaming serialization.

75. Explain CQRS and how to implement it with MediatR in ASP.NET Core.

Separate read and write models. MediatR sends commands/queries. Register services.AddMediatR, create handlers.

76. How do you use Polly for resilient HTTP calls?

Use IHttpClientFactory with AddPolicyHandler for retry, circuit breaker. HttpClient gets resilience automatically.

77. What are background tasks in ASP.NET Core? Implement a recurring job.

Use IHostedService or BackgroundService. For recurring, use PeriodicTimer inside the loop.

78. How do you use SignalR for real‑time notifications?

Add services.AddSignalR(), map a hub (app.MapHub<ChatHub>("/chat")). Clients connect and can send/receive messages.

79. Design a microservice communication pattern with gRPC.

Use Grpc.AspNetCore server, define .proto files. Client uses GrpcChannel. Extremely performant for internal services.

80. How do you containerize an ASP.NET Core app with Docker? Write a Dockerfile.
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
WORKDIR /app
EXPOSE 80
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
...
COPY . .
RUN dotnet publish -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "MyApp.dll"]
81. What is the difference between a Docker image and a container?

Image is a blueprint, container is a running instance of the image.

82. How do you manage secrets in development and production?

Development: Secret Manager tool. Production: Azure Key Vault, environment variables, or Kubernetes secrets.

83. Explain the Options pattern and how to bind configuration to a POCO class.

Use services.Configure<MySettings>(Configuration.GetSection("MySettings")) and inject IOptions<T> / IOptionsSnapshot<T>.

84. How would you implement a health check that verifies database connectivity?

Use AddHealthChecks().AddDbContextCheck<AppDbContext>() or custom IHealthCheck with DbContext.Database.CanConnectAsync().

85. What are the best practices for logging in a microservice?

Structured logging (Serilog), correlation IDs, centralized logging (ELK, Seq). Use ILogger<T> with semantic parameters.

86. How do you configure multiple authentication schemes (JWT + cookies)?

Register both schemes and use [Authorize(AuthenticationSchemes = "Bearer, Cookies")] or policy combining them.

87. What is a resource filter and how is it different from action filters?

Resource filters run before model binding and can short‑circuit the pipeline (e.g., caching). Action filters run before and after action execution.

88. Design an API that supports both JSON and XML responses based on Accept header.

Add XML formatters: services.AddControllers().AddXmlDataContractSerializerFormatters(); The framework automatically selects formatter based on Accept header.

89. How do you implement rate limiting in .NET 7+?

Use built‑in rate limiting middleware: builder.Services.AddRateLimiter(options => { ... }); app.UseRateLimiter(); with fixed window or token bucket policy.

90. What is the role of the IApplicationBuilder in configuring the pipeline?

It is used to add middleware components in the Configure method. In .NET 6+ the WebApplication itself is the builder.

91. How do you protect against Cross‑Site Request Forgery (CSRF) in ASP.NET Core?

For MVC/Razor Pages, use [ValidateAntiForgeryToken] and the <form asp-antiforgery="true"> tag helper.

92. Explain the usage of the [AllowAnonymous] attribute.

It overrides any global [Authorize] attribute, allowing anonymous access to specific actions/controllers.

93. What is a view component and how does it differ from a partial view?

View components have their own logic and can be used like controls. They support parameter passing and async operations, unlike partial views.

94. How do you implement a distributed cache with Redis?

Add services.AddStackExchangeRedisCache(options => { ... }); and inject IDistributedCache. Use SetStringAsync/GetStringAsync.

95. Create a custom middleware that validates a JWT from a custom header and sets the user.

Extract token from header, validate using JwtSecurityTokenHandler, create ClaimsPrincipal and set context.User.

96. What is the difference between IIS and Kestrel hosting?

Kestrel is cross‑platform, fast. IIS can act as a reverse proxy. In production often combined (Kestrel behind IIS/nginx).

97. How do you implement request response logging middleware?

Intercept response body stream, log request and response details. Use EnableBuffering() to allow reading the body multiple times.

98. What are the new minimal API features in .NET 7/8?

Parameter binding with [AsParameters], endpoint filters, typed results, and OpenAPI improvements.

99. How do you test a controller using integration tests with WebApplicationFactory?

Create a test project, use WebApplicationFactory<Program>, create HttpClient and assert responses. Can replace services with fakes.

100. Explain the concept of attribute routing vs conventional routing.

Attribute routing defines routes directly on actions/controllers; conventional routing defines patterns in Program.cs. Both can coexist.

101. How do you handle file downloads with resume support?

Use Range header, read file with offset, set Accept-Ranges and Content-Range headers. Or use FileStreamResult with enableRangeProcessing: true.

102. What is a Typed HttpClient and why is it beneficial?

Inject a class that wraps HttpClient, configured with base address and headers. Provides strong typing and centralized configuration.

103. How do you use Serilog for structured logging?

Add Serilog.AspNetCore, configure in Program.cs with Log.Logger = new LoggerConfiguration()..., then builder.Host.UseSerilog().

104. What is the purpose of the IStartupFilter?

Allows adding extra middleware at the start or end of the pipeline without modifying Startup directly. Useful for libraries.

105. How do you implement a custom authentication handler?

Inherit AuthenticationHandler<TOptions>, implement HandleAuthenticateAsync, and register with AddScheme.

106. Design a notification system that sends emails asynchronously after a user registers.

Use BackgroundService or a message queue (RabbitMQ/Service Bus) to decouple. API publishes a message, worker sends email.

107. How do you measure and improve cold start time in a containerised app?

Use ReadyToRun publish, application trimming, lazy loading of modules, and Docker image layering optimizations.

108. What is the IHostedService vs BackgroundService difference?

BackgroundService is an abstract class simplifying IHostedService implementation with ExecuteAsync.

109. How do you secure a SignalR hub using JWT?

Add AddJwtBearer and configure the hub. In the client, send access token as query string access_token= or via header (WebSockets).

110. Explain how IAsyncEnumerable can be used in an API controller to stream data.

Return IAsyncEnumerable<T> from an action. The framework serializes each item as it’s yielded, reducing memory pressure.

111. What is the difference between UseRouting and UseEndpoints?

UseRouting matches route to endpoint; UseEndpoints executes the matched endpoint. Middlewares like auth go between them.

112. How do you apply the Decorator pattern in ASP.NET Core DI?

Use Scrutor or manual registration: services.Decorate<IService, DecoratorService>() to wrap an implementation.

113. What are the benefits of using IOptionsSnapshot<T> over IOptions<T>?

IOptionsSnapshot reloads configuration per request, supporting changes without restart.

114. How do you implement API key authentication with policy-based authorization?

Create a requirement and handler that validates API key from header, then add [Authorize(Policy = "ApiKey")].

115. Explain forward headers middleware and why it's needed behind a reverse proxy.

Use app.UseForwardedHeaders() to update request scheme, IP from proxy headers (X-Forwarded-For, X-Forwarded-Proto).

116. How do you implement a custom output formatter for CSV?

Derive from TextOutputFormatter, override WriteResponseBodyAsync, register in MvcOptions.OutputFormatters.

117. How would you design an API that needs to support webhooks?

Register webhook endpoints, verify signature, enqueue to a background processor, and respond 200 quickly to avoid timeout.

118. What is the WebApplication.CreateBuilder doing behind the scenes?

Sets up default configuration sources, logging, Kestrel, IIS integration, host builder defaults, and DI container.

119. How can you improve performance by using compiled regex and source generators?

Use [GeneratedRegex] in .NET 7+ to produce compile‑time source generated regex, reducing startup cost.

120. How do you handle large JSON payloads efficiently in an API?

Use streaming deserialization with System.Text.Json DeserializeAsyncEnumerable to process objects one by one.

🔴 Expert Level (5‑10 years) – 60 Questions

121. Design a highly available order processing microservice using ASP.NET Core, Azure Service Bus, and Dapr.

Use Dapr pub/sub with Service Bus, ASP.NET Core API for commands, background service for events, saga pattern for distributed transactions, and Azure Cosmos DB for state store.

122. How would you implement the Outbox pattern to ensure reliable messaging?

Save events in the same database transaction as entity change. A background worker polls the outbox table and publishes to a message broker.

123. What is the difference between Serverless and container‑based deployment for ASP.NET Core?

Serverless (Azure Functions / AWS Lambda) scales to zero, cost‑effective for infrequent use; containers run 24/7 but give full control. Choose based on workload pattern.

124. How do you implement a distributed transaction using the Saga pattern?

Choreography: services listen to events and react. Orchestration: a central saga manager coordinates. ASP.NET Core can be the orchestrator.

125. Explain how to achieve zero downtime deployment on Kubernetes with ASP.NET Core.

Use rolling updates, health probes, graceful shutdown (IApplicationLifetime), readiness probes with HealthCheck endpoints.

126. How do you implement custom middleware that adds correlation ID and propagates it to downstream services?

Generate/read X-Correlation-ID header, store in AsyncLocal or Activity.Current, inject into HTTP client headers using DelegatingHandler.

127. What are the key considerations when designing gRPC services for mobile clients?

Use gRPC‑Web, smaller messages, client‑side streaming with cancellation, protobuf well‑known types. Consider fallback to JSON REST for older devices.

128. How do you secure inter‑service communication in a Kubernetes cluster?

Use mTLS via a service mesh (Linkerd, Istio), or use JWT tokens with short expiry. ASP.NET Core can validate certificates.

129. Design an event‑driven architecture using Kafka and ASP.NET Core.

Use Confluent.Kafka client library. Build background services that consume Kafka topics and produce new events. Idempotency handling required.

130. How do you implement the circuit breaker pattern with ASP.NET Core and Polly?

Configure AddPolicyHandler with HttpCircuitBreakerPolicy wrapping the HTTP call. Breaks the circuit after a number of failures.

131. What is the best strategy for API gateway pattern using Ocelot or YARP?

YARP is more performant. Configure routes and clusters in config. Add auth, rate limiting, load balancing. ASP.NET Core app becomes the gateway.

132. How do you implement query optimization with Entity Framework Core for a dashboard with millions of rows?

Use no‑tracking queries, raw SQL, indexed views, materialized views, and read replicas. Consider ADO.NET for complex reports.

133. What are the challenges of multi‑tenancy and how do you solve them?

Database per tenant vs shared. Use ITenantProvider middleware that resolves tenant from host/header. Filter queries by tenant ID. Use row‑level security.

134. How do you implement a feature toggle service using ASP.NET Core?

Use Microsoft.FeatureManagement. Register AddFeatureManagement(). Use IFeatureManager or [FeatureGate] attribute. Connect to Azure App Configuration for dynamic toggles.

135. Explain how to use Azure Key Vault to securely store connection strings and rotate secrets.

Add Azure.Security.KeyVault.Secrets, configure builder.Configuration.AddAzureKeyVault(...). Secrets are loaded into IConfiguration. Automatic rotation with reload on change.

136. How do you implement a custom IValueResolver in AutoMapper for a business rule?

Create a class implementing IValueResolver<Source, Dest, string> with business logic, register in profile. This keeps mapping logic separate.

137. Design a real‑time collaborative document editor using SignalR and operational transformation.

Use SignalR hub to broadcast changes, implement OT or CRDT algorithm on the server for conflict resolution, persist snapshots periodically.

138. How would you implement background job processing with Hangfire in an ASP.NET Core app?

Add Hangfire with AddHangfire/AddHangfireServer, store jobs in SQL Server. Enqueue jobs: BackgroundJob.Enqueue(() => service.DoWork());

139. What is the dual‑write problem and how do you solve it using Change Data Capture (CDC)?

Instead of writing to DB and message broker separately, use CDC (Debezium) to stream DB changes to Kafka, ensuring consistency.

140. How do you implement an API that supports GraphQL with Hot Chocolate?

Add HotChocolate.AspNetCore, define types and queries. Map GraphQL endpoint with app.MapGraphQL(). Use data loaders to avoid N+1.

141. What are the performance implications of IHttpClientFactory vs static HttpClient?

Static HttpClient doesn't honor DNS changes; factory provides fresh connections via SocketsHttpHandler pooling, avoids socket exhaustion.

142. How do you create a custom IHostedService that scales out across multiple instances using a distributed lock?

Use Redis RedLock or Azure Lease Blob to ensure only one instance runs the job. Acquire lock in ExecuteAsync.

143. Design an ASP.NET Core middleware that blocks requests from blacklisted IPs.

Check context.Connection.RemoteIpAddress against a cached blacklist. Return 403 if matched. Update blacklist via a background service pulling from a store.

144. How do you use ActivitySource and OpenTelemetry for distributed tracing?

Add OpenTelemetry.Extensions.Hosting. Configure tracing with AddSource("myapp"), AddAspNetCoreInstrumentation(), export to Jaeger/Azure Monitor.

145. What is the best way to handle long‑running requests that require high availability?

Use asynchronous polling or webhooks, with durable background processing (Azure Durable Functions) so the client doesn’t block.

146. How would you implement a data seeding strategy for different environments using EF Core?

Use ModelBuilder.HasData() for development. For production, run a console app or migration with custom SQL. Use environment‑specific seeding.

147. Explain how to implement pagination with cursor‑based approach instead of offset.

Use a unique sequential column (e.g., Id). Return next cursor token (base64 encoded ID) and query WHERE Id > @cursor. More consistent under concurrent inserts.

148. How do you design an API that needs to support both REST and gRPC on the same port?

Configure Kestrel with HTTP/2 and TLS. Use endpoint routing to map both gRPC services and API controllers. gRPC‑JSON transcoding can bridge them.

149. What are the security best practices for storing JWT refresh tokens?

Store in HttpOnly secure cookie, with same‑site strict, or encrypted in a database. Rotate refresh tokens on each use.

150. How do you implement a feature flag that turns on AI‑based recommendations for a subset of users?

Use a feature filter: context.TargetingContext.UserId. In handler, call AI service only if feature enabled for user. Gradually roll out.

151. Design a fault‑tolerant API that gracefully degrades when a downstream AI service is unavailable.

Implement fallback using Polly’s FallbackPolicy returning cached results or empty recommendations. Circuit breaker opens after failures.

152. How do you use Azure Cognitive Search to implement full‑text search with faceted navigation?

Create index, use Azure.Search.Documents client in ASP.NET Core service. Build query with SearchOptions { Facets = { "category" } }.

153. What is the concept of "right‑sizing" microservices and how do you decide boundaries?

Identify bounded contexts (domain‑driven design). Each microservice owns its data. Use event storming to map business capabilities.

154. How do you implement blue‑green deployment for an ASP.NET Core app on Azure?

Use deployment slots in App Service. Deploy new version to staging slot, warm it up, then swap. Monitor with application insights.

155. What is the effect of ThreadPool starvation and how to prevent it in ASP.NET Core?

Avoid sync‑over‑async, always use async all the way. Use ConfigureAwait(false) in library code. Monitor ThreadPool.GetAvailableThreads.

156. How do you implement custom JSON converters for polymorphic serialization?

Create a JsonConverter for the base type, read a discriminator property, and deserialize to the correct derived type.

157. Design a system that uses ASP.NET Core to host multiple tenant‑specific APIs on different subdomains.

Use IApplicationBuilder.MapWhen or YARP proxy to route based on host. Use ITenantResolutionStrategy.

158. How would you implement a localisation strategy for a multi‑language API?

Use IStringLocalizer with resource files. Respond with error messages in Accept-Language header language.

159. What is the role of IServer abstraction in ASP.NET Core?

It allows hosting on different servers (Kestrel, HTTP.sys, IIS). Implementations handle request listening.

160. How do you implement server‑sent events (SSE) for a dashboard that streams real‑time data?

Keep response stream open, write data: ...\n\n periodically. Use Response.Body.FlushAsync(). Need to handle client disconnects.

161. How would you leverage Azure Durable Functions with ASP.NET Core for long‑running workflows?

ASP.NET Core API receives request, starts an orchestration via HTTP trigger. The orchestration can call activity functions. Use DurableTaskClient.

162. What are the key differences between transactional outbox and inbox pattern?

Outbox ensures message publication within the transaction. Inbox deduplicates incoming messages to achieve exactly‑once processing.

163. How do you configure a production‑grade logging pipeline with Elasticsearch and Kibana?

Use Serilog with Elasticsearch sink. ASP.NET Core logs go directly to Elastic, visualized in Kibana. Add structured log properties.

164. Explain how to implement the API composition pattern for a mobile backend for frontend (BFF).

Create a dedicated ASP.NET Core service that aggregates data from multiple microservices and tailors the response for the mobile client.

165. How do you detect and prevent distributed denial‑of‑service (DDoS) attacks at the application level?

Use rate limiting, early detection of abuse patterns, integrate with Azure DDoS Protection, and monitor anomalies with Application Insights.

166. What is the purpose of the DiagnosticSource and Activity classes?

They enable rich distributed tracing. ASP.NET Core uses ActivitySource for incoming requests; libraries produce activities.

167. How do you implement a custom IActionResultExecutor for a new response type?

Implement the interface, register with DI, and use it to execute a custom ActionResult that writes directly to the response stream.

168. Design an API that supports both sync and async endpoints for legacy clients.

Provide sync wrapper using Task.Run only if absolutely necessary, but encourage client to upgrade. Document transition.

169. How do you use Azure Application Insights to monitor dependency calls and exceptions?

Add Microsoft.ApplicationInsights.AspNetCore. It auto‑collects requests, dependencies, exceptions. Custom telemetry via TelemetryClient.

170. What are the best practices for managing database migrations in a team using EF Core?

Use version‑controlled migrations, avoid auto‑generation during build, have a dedicated migration assembly, and merge carefully to avoid conflicts.

171. How would you build a custom NuGet package that provides a middleware for request auditing?

Create a class library with a IApplicationBuilder extension method. Package as NuGet. Users call app.UseRequestAudit().

172. Explain the difference between a vertical slice architecture and clean architecture.

Vertical slice organizes by feature (not layers). ASP.NET Core with MediatR naturally fits vertical slices. Clean architecture separates domain, application, infrastructure.

173. How do you implement an API that uses the Strangler Fig pattern to migrate from legacy?

Place a proxy (YARP) in front. Route new endpoints to ASP.NET Core; old ones to legacy system. Gradually replace legacy endpoints.

174. What is the impact of JSON serialization settings on API performance and how to optimize?

Use System.Text.Json with source generators, avoid JsonSerializerOptions per call. Enable WriteIndented=false.

175. How do you implement a sidecar container for logging/monitoring in Kubernetes?

Add a sidecar that collects logs from the app container (stdout) or shared volume, and forwards to central storage.

176. Design an authentication‑as‑a‑service microservice that issues JWT for multiple applications.

Use IdentityServer4/Duende. ASP.NET Core hosts the identity provider. Apps redirect for login and receive tokens.

177. How do you ensure idempotency for a payment processing endpoint?

Client sends an Idempotency-Key. Server stores the response for that key and returns it for duplicates. Use a cache with sliding expiration.

178. What are the trade‑offs of using a relational database vs NoSQL for a product catalog?

Relational for strong consistency, complex queries. NoSQL (Cosmos DB) for schema flexibility, horizontal scaling. Can combine both in CQRS.

179. How do you implement real‑time analytics dashboard using ASP.NET Core and Azure Stream Analytics?

Ingest events via Event Hub, process with ASA, output to Power BI or a SignalR hub that broadcasts to clients.

180. What is the difference between the HostBuilder and WebApplicationBuilder?

WebApplicationBuilder adds web‑specific defaults. It’s the modern way to build web apps, replacing manual host creation.

👑 Most Expert / Architect (10+ years) & AI‑Oriented – 40 Questions

181. How do you integrate Azure OpenAI GPT‑4 into an ASP.NET Core app to add AI‑powered search?

Use Azure.AI.OpenAI client, registered as singleton. Create embeddings for documents stored in Azure Cognitive Search. On search, embed user query, find similar docs, then ask GPT to summarise. Implement semantic caching with Semantic Kernel.

182. Design a multi‑tenant SaaS application with AI‑based anomaly detection for each tenant.

Per‑tenant ML model using ML.NET in a background service, or call Azure Anomaly Detector. Train on tenant‑specific data. Use ITenantProvider to load correct model. Expose alerts via SignalR.

183. How do you use ML.NET inside an ASP.NET Core service to predict customer churn?

Train a model and save it as a .zip. Load in a singleton PredictionEnginePool. Inject PredictionEnginePool<Input, Output> and call _pool.Predict(input).

184. Explain how to build a RAG (Retrieval‑Augmented Generation) application using ASP.NET Core.

Use a vector database (Qdrant). On document upload, chunk, compute embeddings, store. On query, retrieve similar chunks, send as context to GPT. Implement via Semantic Kernel or LangChain.NET.

185. How would you implement a chatbot that can execute SQL queries on a database using NL2SQL with AI?

Use Azure OpenAI to convert natural language to SQL (with schema context), execute via EF Core raw SQL, return results. Implement safety checks and read‑only permissions.

186. What are the ethical concerns and mitigation strategies when embedding AI in financial applications?

Bias, transparency, explainability. Use Microsoft.Fairlearn for model evaluation. Log AI decisions with reasoning. Provide human override.

187. How do you monitor and fine‑tune an AI model deployed in an ASP.NET Core service?

Collect prediction telemetry with Application Insights. Track accuracy drift. Implement feedback loop – if user corrects, store for retraining.

188. Design a system that automatically generates code documentation from an ASP.NET Core API using AI.

Reflect on endpoints, extract XML comments, feed to GPT to produce OpenAPI description enhancements. Use a background job triggered on build.

189. How do you implement a recommendation engine that updates in real‑time using ASP.NET Core and ML.NET?

Use Matrix Factorization model. Retrain periodically with new data. Serve predictions via API. Use ChangeDataCapture to update training data incrementally.

190. What is the role of Semantic Kernel in orchestrating AI plugins within an ASP.NET Core app?

Semantic Kernel allows chaining AI functions (plugins) together. Register plugins as services, define a kernel plan, execute it to fulfill user intent.

191. How do you securely handle API keys for AI services in a team development environment?

Use Secret Manager in dev, Azure Key Vault in prod. Never commit to source control. Use managed identities to avoid keys where possible.

192. Design an ASP.NET Core service that uses Azure Cognitive Services for image moderation.

Accept upload, send to ContentModeratorClient, evaluate response, block if inappropriate. Use async processing for large batches.

193. How do you implement A/B testing for an AI feature in an ASP.NET Core application?

Use feature flags with target filters. Randomly assign user to variant. Track business metrics in telemetry. Compare cohorts.

194. What are the challenges of using LLMs in production and how do you address them with ASP.NET Core?

Latency, cost, output consistency. Use caching, streaming, fine‑tuning, and content safety filters. Implement retry with exponential backoff.

195. How can you combine Azure OpenAI with Azure Speech Services to build a voice‑enabled API?

Accept audio stream, convert speech to text using Speech SDK, send text to GPT, convert response text to speech, stream back. ASP.NET Core handles WebSocket streaming.

196. Design a system that uses AI to automatically categorize support tickets and suggest solutions.

Classify text with ML.NET multiclass classifier. Integrate into ticket API. Suggest similar resolved tickets using TF‑IDF + cosine similarity.

197. How do you implement rate limiting for an expensive AI endpoint to control costs?

Use built‑in rate limiter with partition per user. Return 429; client backs off. Track usage and enforce quotas via Azure API Management.

198. What is the best approach to handle long‑running AI tasks (e.g., model training) from an ASP.NET Core request?

Offload to a background job (Hangfire, Durable Functions). Return a status endpoint to poll for completion. Do not block the request thread.

199. How would you build a pluggable architecture where different AI providers can be swapped easily?

Define an interface IAIService. Implement for OpenAI, Azure, etc. Use factory pattern. Configure via DI. Makes it cloud‑agnostic.

200. Explain how to use vector embeddings for semantic search in an e‑commerce ASP.NET Core app.

Generate embeddings for product descriptions with Azure.AI.OpenAI, store in pgvector or Cosmos DB with vector index. Search using cosine similarity. Return sorted products.

201. How do you ensure data privacy when processing user data with AI models?

Use on‑premises/open‑source models for sensitive data, or Azure with data residency guarantees. Anonymise PII before sending to AI. Comply with GDPR.

202. Design an ASP.NET Core middleware that adds AI‑powered response suggestions to API error messages.

On exception, capture context, ask GPT for a user‑friendly error message and possible fix suggestions, then return a custom problem+json.

203. How would you implement a custom model cache for frequently used AI prompts?

Use IMemoryCache with prompt hash as key. Store completion. Set expiration based on content freshness. Could use distributed cache for multi‑instance.

204. What are the security implications of prompt injection in AI‑integrated apps?

Sanitize and validate user input, use prompt templates that separate instructions from user data, implement output filtering and content safety checks.

205. How do you track cost and token consumption per user for Azure OpenAI in a multi‑tenant app?

Log Usage object from response. Store in a cost tracking table. Implement quota enforcement logic to block users exceeding budget.

206. Design an API that uses AI to generate unit tests for given code snippets.

Accept code string, send to GPT with instructions, return test code. Validate generated test with compilation API before returning. Add sandbox execution.

207. How can you leverage AI to improve the developer experience of your own ASP.NET Core team?

Build internal chatbots for docs, automated code review using AI, and integration with CI/CD to suggest improvements.

208. What is the future of AI‑assisted coding within ASP.NET Core, and how would you prepare your architecture?

Adopt modular, API‑first design so AI can easily compose workflows. Use semantic annotations. Focus on clear contracts (OpenAPI) that AI tools can consume.

209. How do you implement a real‑time translation API using Azure AI Translator and ASP.NET Core?

Client sends text and target language. Service calls Translator API, caches results. For streaming, use SignalR to deliver translations as they arrive.

210. Design a “smart” caching layer that uses AI to predict what data to pre‑warm before peak hours.

Analyze historical request patterns with ML.NET time series. Predict hot items and pre‑load cache (Redis) via a scheduled background service.

211. How do you integrate Azure Form Recognizer into an invoice processing API?

Accept uploaded document, send to Form Recognizer, parse response to extract fields. Store structured data in DB. Use async pattern with callback or status poll.

212. What are the best practices for prompt engineering in a production ASP.NET Core service?

Use system/user/assistant roles, separate instructions clearly, provide examples, set temperature and max_tokens. Version prompts in config.

213. How do you implement an AI‑driven dynamic pricing engine in an e‑commerce platform?

ASP.NET Core API calls ML model that recommends price based on demand, competition, inventory. Use background worker to adjust prices in DB.

214. How can you use AI to detect and block malicious requests in your ASP.NET Core pipeline?

Middleware that scores request based on ML model trained on attack patterns (SQL injection, XSS). High‑risk requests are blocked.

215. Design a low‑latency AI inference service that serves multiple models with ASP.NET Core.

Load models into memory at startup. Use ObjectPool of prediction engines for high throughput. Route requests to correct model via path or header.

216. How do you implement a feedback loop for an AI recommendation system using ASP.NET Core?

Capture user interactions (clicks, purchases) as events. Store in event store. Periodically retrain model and redeploy. A/B test new vs old.

217. What is model explainability, and how do you add it to an API response?

Use Microsoft.ML.Explainability to get feature contributions. Include explanation in API response so users understand why a decision was made.

218. How do you version AI models alongside your API versions?

Add model version to API path or header. Register multiple implementations of prediction service. Use feature flags to route to specific model version.

219. Design a resilient AI workflow that continues to serve even if the primary AI service is down.

Primary Azure OpenAI, fallback to a locally hosted smaller model (e.g., Phi‑2) via ONNX runtime. Circuit breaker switches to fallback.

220. What does an AI‑first architecture look like for a modern ASP.NET Core web application?

Every feature is built with AI integration points: semantic search, personalized content, automated moderation, intelligent alerts. AI services are first‑class dependencies. Observability and ethics are foundational.

⚡ Ready to Land Your Dream Job?

Access 3000+ real interview questions, AI‑powered mock interviews, and expert feedback.

🎯 Go to Job Interview Portal Now

Post a Comment

0 Comments