ASP.net Core Interview Question & Answers
ASP.net Core Interview Question & Answers
Pipeline Flow:
Key Components:
Code Example:
csharp
CopyEdit
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
endpoints.MapControllers();
});
csharp
CopyEdit
_next = next;
// Pre-processing logic
// Post-processing logic
return builder.UseMiddleware<CustomMiddleware>();
o Usage:
csharp
CopyEdit
app.UseCustomMiddleware();
IApplicationBuilder:
IServiceCollection:
Key Differences:
How It Works:
Example:
csharp
services.AddSingleton<IMyService, MyService>();
services.AddScoped<DbContext>();
_myService = myService;
IHostedService:
BackgroundService:
When to Use:
Example of BackgroundService:
csharp
CopyEdit
while (!stoppingToken.IsCancellationRequested)
services.AddHostedService<MyBackgroundService>();
Advanced Topics
In-Memory Caching
Implementation:
csharp
CopyEdit
services.AddMemoryCache();
_cache = cache;
[HttpGet]
cachedValue = DateTime.Now.ToString();
return Ok(cachedValue);
Distributed Caching
Implementation:
csharp
CopyEdit
services.AddStackExchangeRedisCache(options =>
options.Configuration = "localhost:6379";
});
_cache = cache;
[HttpGet]
if (string.IsNullOrEmpty(cachedValue))
cachedValue = DateTime.Now.ToString();
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
});
return Ok(cachedValue);
Response Caching
Implementation:
csharp
CopyEdit
services.AddResponseCaching();
app.UseResponseCaching();
[HttpGet]
[ResponseCache(Duration = 60)]
Model Binding:
Purpose: Maps incoming request data (e.g., query strings, form data,
route data) to controller action parameters or model properties.
Customization:
csharp
CopyEdit
var value =
bindingContext.ValueProvider.GetValue("customKey").FirstValue;
return Task.CompletedTask;
Model Validation:
Customization:
csharp
CopyEdit
if (value.ToString() == "Invalid")
return ValidationResult.Success;
Implementation:
csharp
CopyEdit
[Timestamp]
2. Pessimistic Concurrency:
3. Critical Section:
Implementation:
csharp
CopyEdit
lock (_lock)
4. Distributed Locking:
WebHostBuilder:
Used in ASP.NET Core 2.x and earlier for hosting web applications.
Example:
csharp
CopyEdit
.UseKestrel()
.UseStartup<Startup>()
.Build();
host.Run();
GenericHostBuilder:
Example:
csharp
CopyEdit
.ConfigureWebHostDefaults(webBuilder =>
webBuilder.UseStartup<Startup>();
})
.Build();
host.Run();
Key Differences:
Key Takeaway
Performance Optimization
2. Profiling Tools:
4. Database Performance:
Optimization Techniques:
1. Caching:
2. Reduce Payload:
3. Asynchronous Programming:
4. Load Balancing:
12. What Are Some Best Practices for Improving the Performance of
APIs in ASP.NET Core?
2. Minimize Overhead:
3. Leverage Caching:
4. Reduce Latency:
6. Asynchronous Operations:
Rate limiting prevents excessive API requests, ensuring fair resource usage
and protecting against abuse.
Using Middleware:
csharp
CopyEdit
_next = next;
if (!RequestCounts.ContainsKey(ipAddress))
RequestCounts[ipAddress] = 0;
return;
await _next(context);
builder.UseMiddleware<RateLimitingMiddleware>();
Using Libraries:
Example:
csharp
CopyEdit
services.AddInMemoryRateLimiting();
services.AddSingleton<IRateLimitConfiguration,
RateLimitConfiguration>();
14. What Tools and Methods Do You Use for Profiling an ASP.NET
Core Application?
1. Built-In Tools:
3. Third-Party Tools:
4. Cloud-Based Monitoring:
5. Analyzing Logs:
1. Dispose Resources:
3. Minimize Boxing/Unboxing:
json
CopyEdit
"runtimeOptions": {
"configProperties": {
"System.GC.Server": true,
"System.GC.RetainVM": false
For a senior role, emphasize your ability to identify, analyze, and resolve
performance bottlenecks while following best practices. Showcase your
knowledge of tools, frameworks, and techniques to maintain highly
performant and scalable ASP.NET Core applications.
Security
Authentication:
Implementation involves:
Authorization:
1. Role-based Authorization:
csharp
CopyEdit
2. Policy-based Authorization:
csharp
CopyEdit
services.AddAuthorization(options =>
policy.RequireRole("Admin"));
});
3. Claims-based Authorization:
csharp
CopyEdit
policy.RequireClaim("Age", "18"));
Cookie-Based
Aspect JWT Authentication
Authentication
18. Explain How to Secure an ASP.NET Core API Using OAuth 2.0 and
OpenID Connect
csharp
CopyEdit
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
});
2. Configure Authorization:
csharp
CopyEdit
[Authorize]
[HttpGet("secure-data")]
o Integrate with identity providers like Azure AD, Auth0, or Okta for
authentication and user info.
csharp
CopyEdit
services.AddAuthentication(options =>
options.DefaultScheme =
CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme =
OpenIdConnectDefaults.AuthenticationScheme;
})
.AddOpenIdConnect(options =>
options.Authority = "https://example.com";
options.ClientId = "client-id";
options.ClientSecret = "client-secret";
options.ResponseType = "code";
});
4. Validate Tokens:
csharp
CopyEdit
services.AddCors(options =>
builder.WithOrigins("https://trusted.com")
.AllowAnyMethod()
.AllowAnyHeader());
});
csharp
CopyEdit
app.UseCors("AllowSpecificOrigins");
3. Per-Controller or Action:
csharp
CopyEdit
[EnableCors("AllowSpecificOrigins")]
1. Enforce HTTPS:
csharp
CopyEdit
app.UseHttpsRedirection();
2. Use Certificates:
bash
CopyEdit
csharp
CopyEdit
app.UseHsts();
Mutual Authentication:
csharp
CopyEdit
webBuilder.ConfigureKestrel(options =>
options.ConfigureHttpsDefaults(o =>
o.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
});
});
Secure Protocols:
csharp
CopyEdit
webBuilder.ConfigureKestrel(serverOptions =>
serverOptions.ConfigureHttpsDefaults(httpsOptions =>
});
});
Key Takeaway
csharp
CopyEdit
.ToList();
2. Leverage LINQ-to-Entities:
csharp
CopyEdit
.ToList();
csharp
CopyEdit
.ToList();
4. Pagination:
csharp
.Skip(10)
.Take(10)
.ToList();
5. Database Indexing:
6. Projection:
csharp
CopyEdit
.ToList();
Example:
csharp
CopyEdit
// Tracking
// AsNoTracking
bash
CopyEdit
3. Manage Downtime:
o Use the HasData method for initial data setup, but avoid large
data sets in migrations.
csharp
CopyEdit
6. Migration Execution:
csharp
CopyEdit
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
2. Connection Pooling:
csharp
sqlOptions.EnableRetryOnFailure());
4. Limit Connections:
5. Retry Policies:
csharp
CopyEdit
options.EnableRetryOnFailure(maxRetryCount: 5);
6. Async Operations:
csharp
CopyEdit
csharp
CopyEdit
await context.BulkInsertAsync(entities);
2. Batch Processing:
csharp
CopyEdit
context.AddRange(batch);
await context.SaveChangesAsync();
3. SQL Operations:
csharp
CopyEdit
csharp
CopyEdit
context.ChangeTracker.AutoDetectChangesEnabled = false;
5. Optimize SaveChanges:
csharp
CopyEdit
context.SaveChanges();
Key Takeaway
Technology Stack: Use ASP.NET Core Web API for lightweight, cross-
platform microservices, leveraging built-in dependency injection,
configuration, and middleware.
27. What Are the Pros and Cons of Monolithic vs. Microservices
Architecture?
gRPC:
SignalR:
Role:
Implementation:
csharp
CopyEdit
app.UseOcelot().Wait();
Distributed Logging:
Distributed Tracing:
Implementation:
Summary
Azure Deployment:
o Publish directly from Visual Studio or via CLI (az webapp deploy).
AWS Deployment:
Elastic Beanstalk:
Docker:
Kubernetes:
CI Pipeline:
CD Pipeline:
Environment Variables:
Configuration Providers:
35. How Would You Use Azure Functions or AWS Lambda with
ASP.NET Core?
AWS Lambda:
Summary
With 17+ years of experience, I leverage cloud platforms like Azure and AWS
to deploy and scale ASP.NET Core applications efficiently. Docker and
Kubernetes are pivotal for modern containerized deployments, while CI/CD
pipelines automate quality and delivery. Secure secrets management and
serverless integrations (Azure Functions/AWS Lambda) complement scalable,
resilient, and cost-effective architectures.
Frontend Integration
Development Experience:
37. What Are the Pros and Cons of Server-Side Rendering vs. Client-
Side Rendering in ASP.NET Core?
Client-Side Rendering
Aspect Server-Side Rendering (SSR)
(CSR)
Separate Endpoints:
Example:
csharp
CopyEdit
app.UseEndpoints(endpoints =>
});
csharp
CopyEdit
services.AddCors(options =>
builder.WithOrigins("https://yourfrontenddomain.com")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
csharp
CopyEdit
app.UseCors("AllowFrontend");
In ASP.NET Core:
Benefits:
Summary
Stateless Design:
Architect the app to be stateless where possible, meaning no reliance
on in-memory session state or server affinity. This facilitates scaling
out across multiple servers.
Asynchronous Programming:
Use async/await throughout to efficiently handle I/O-bound operations
and maximize thread usage.
Caching:
Implement caching at multiple layers (response caching, in-memory,
distributed cache like Redis) to reduce database hits and improve
response times.
42. What Strategies Do You Use for Horizontal and Vertical Scaling
in ASP.NET Core?
Implementation Details:
Kestrel Considerations:
Graceful Degradation:
Design services to fail gracefully, returning appropriate fallback
responses or cached data.
Health Checks:
Implement ASP.NET Core health checks to monitor the status of
dependencies (databases, external services) and enable load balancers
to route traffic away from unhealthy instances.
Benefits:
Implementation Tips:
Summary
Miscellaneous
Approaches:
Implementation:
Use the official Microsoft.AspNetCore.Mvc.Versioning package to
implement flexible versioning strategies, supporting multiple schemes.
Best Practices:
48. Explain the Differences Between .NET Framework and .NET Core
Installed globally on
Deployment Self-contained deployment option
Windows
Container
Limited Native container support
Support
Key Features:
Implementation Steps:
50. What Are the New Features in the Latest Version of ASP.NET
Core That You’ve Worked With?
Output Caching:
Native output caching middleware for better response performance.
Summary