Master technical and career interviews with structured answers—short definition, real examples, pitfalls, and how to answer in 60–90 seconds.
pp.MapHealthChecks("/health"); What interviewers expect A clear definition tied to MVC in ASP.NET Core MVC projects Trade-offs (performance, maintainability, security, cost) When you would and would not use it in product…
Role-based authorization restricts access based on user roles. ssign a role: wait _userManager.AddToRoleAsync(user, "Admin"); Use in controllers: [Authorize(Roles = "Admin")] public IActionResult Dashboard() => View()…
pp.UseExceptionHandler("/Home/Error"); or public class GlobalExceptionFilter : IExceptionFilter { public void OnException(ExceptionContext context) { context.Result = new ViewResult { ViewName = "Error" }; } } 🧩 19. How…
builder.Services.AddHealthChecks(); app.MapHealthChecks("/health"); What interviewers expect A clear definition tied to MVC in ASP.NET Core MVC projects Trade-offs (performance, maintainability, security, cost) When you…
Application Insights provides monitoring, telemetry, and tracing. Setup: builder.Services.AddApplicationInsightsTelemetry(builder.Configurati on["APPINSIGHTS_INSTRUMENTATIONKEY"]); Features: Track requests, exceptions, a…
TestContainers spins up real Docker containers (SQL Server, Redis) for integration testing, simulating production. Example: using Testcontainers.MsSql; var sqlContainer = new MsSqlBuilder() .WithPassword("yourStrong(!)Pa…
EF Core allows using InMemoryDatabase or mocking DbSet<T> to avoid hitting a real database. Example with InMemoryDatabase: var options = new DbContextOptionsBuilder<AppDbContext>() .UseInMemoryDatabase(databa…
Value converters transform data between your entity property and database column type. Example: Store an enum as a string in the DB: modelBuilder.Entity<User>() .Property(u => u.Status) .HasConversion<string&…
Partial views are used to render reusable page sections (like headers, sidebars). Example: public IActionResult ProductList() var products = _service.GetAll(); return PartialView("_ProductListPartial", products); In Razo…
Using SignalR for Real-Time Communication // Hub public class ChatHub : Hub { public async Task SendMessage(string user, string message) => await Clients.All.SendAsync("ReceiveMessage", user, message); } // Client (Ja…
Logging in production should be: Centralized Structured Persistent Low-overhead ASP.NET Core has ILogger interface and supports logging providers like Console, File, Seq, Application Insights. Example: public class HomeC…
You can use: What interviewers expect A clear definition tied to MVC in ASP.NET Core MVC projects Trade-offs (performance, maintainability, security, cost) When you would and would not use it in production Real-world exa…
zure App Service PaaS Easy scaling, HTTPS CI/CD GitHub Actions / Azure DevOps Automated build/test/deploy Logging ILogger, Serilog, NLog Use structured logging Monitoring Application Insights, Prometheus Track metrics, u…
Docker allows running ASP.NET Core apps in containers, portable across environments. Dockerfile Example: # Build stage FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build WORKDIR /app COPY *.csproj ./ RUN dotnet restore COPY…
public class LogActionFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { Console.WriteLine($"Action: {context.ActionDescriptor.DisplayName}"); } } Use it: [LogAction…
ASP.NET Core handles HTTP requests through a middleware pipeline, which is a sequence of components where each can: Inspect or modify the request Call the next middleware Short-circuit the pipeline Pipeline Flow: Request…
Docker allows running ASP.NET Core apps in containers, portable across environments. Dockerfile Example: # Build stage FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build WORKDIR /app COPY *.csproj ./ RUN dotnet restore COPY…
Configuration providers are components that load configuration data from various sources. Built-in Providers: JSON files (appsettings.json) Environment variables Command-line arguments In-memory collections Azure Key Vau…
public class LogActionFilter : ActionFilterAttribute public override void OnActionExecuting(ActionExecutingContext context) Console.WriteLine($"Action: {context.ActionDescriptor.DisplayName}"); Use it: [LogActionFilter]…
Answer: Hangfire or Quartz.NET for Background Jobs Hangfire Example: app.UseHangfireDashboard(); RecurringJob.AddOrUpdate(() =&gt; Console.WriteLine("Recurring job"), Cron.Daily); Quartz.NET: Supports cron-like sched…
How to Test Minimal APIs? Answer: Minimal APIs are tested using WebApplicationFactory or TestServer. Example: var factory = new WebApplicationFactory<Program>(); var client = factory.CreateClient(); var response =…
Health Checking in ASP.NET Core builder.Services.AddHealthChecks() .AddSqlServer(connectionString) .AddCheck<CustomHealthCheck>("CustomCheck"); app.MapHealthChecks("/health"); Custom Health Check Example: public cl…
How to Use Serilog or NLog? Serilog Example (Program.cs): builder.Host.UseSerilog((ctx, lc) => lc .WriteTo.Console() .WriteTo.File("logs/log-.txt", rollingInterval: RollingInterval.Day) ); NLog Example: Install NLog.E…
What Frameworks Are Commonly Used? Answer: xUnit – Popular, lightweight, supports parallel testing. NUnit – Rich assertion library. MSTest – Microsoft-supported, integrated in Visual Studio. Most modern ASP.NET Core proj…
Compiled queries improve performance by caching query translation. Example: private static readonly Func<AppDbContext, decimal, IEnumerable<Product>> _getExpensiveProducts = EF.CompileQuery((AppDbContext ctx,…
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
pp.MapHealthChecks("/health");
In a production ASP.NET Core MVC application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Role-based authorization restricts access based on user roles.
ssign a role:
wait _userManager.AddToRoleAsync(user, "Admin");
Use in controllers:
[Authorize(Roles = "Admin")]
public IActionResult Dashboard() => View();
You can also combine roles:
[Authorize(Roles = "Admin,Manager")]
🧭 7. What is policy-based authorization?
Policy-based authorization gives fine-grained control over access using custom rules.
Instead of just roles, you define policies with specific requirements.
Define a policy:
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdminEmail", policy =>
policy.RequireClaim(ClaimTypes.Email, "admin@myapp.com"));
});
pply policy:
[Authorize(Policy = "RequireAdminEmail")]
public IActionResult AdminOnly() => View();
⚖ 8. How to create custom authorization policies?
You can write custom authorization handlers to evaluate complex logic.
Example:
public class MinimumAgeRequirement : IAuthorizationRequirement
{
public int Age { get; }
public MinimumAgeRequirement(int age) => Age = age;
}
public class MinimumAgeHandler :
uthorizationHandler<MinimumAgeRequirement>
{
protected override Task HandleRequirementAsync(
uthorizationHandlerContext context, MinimumAgeRequirement
requirement)
{
var birthDateClaim = context.User.FindFirst(c => c.Type ==
"BirthDate");
if (birthDateClaim != null)
{
var birthDate = DateTime.Parse(birthDateClaim.Value);
if (birthDate.AddYears(requirement.Age) <=
DateTime.Today)
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
Register it:
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("AdultOnly", policy =>
policy.Requirements.Add(new MinimumAgeRequirement(18)));
});
builder.Services.AddSingleton<IAuthorizationHandler,
MinimumAgeHandler>();
Use it:
[Authorize(Policy = "AdultOnly")]
public IActionResult BuyAlcohol() => Ok("Access granted");
🍪 9. What is cookie authentication in ASP.NET Core?
Cookie authentication stores user information in an encrypted cookie on the browser.
When the user revisits, the cookie is used to identify them.
Configure:
builder.Services.AddAuthentication(CookieAuthenticationDefaults.Auth
enticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Account/Login";
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
});
Once the user logs in:
wait HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(identity));
🌐 10. How to integrate OAuth2 / OpenID Connect in
SP.NET Core?
ASP.NET Core supports external providers like Google, Microsoft, Azure AD, etc. using
OAuth2 and OpenID Connect.
Example for OpenID Connect (Azure AD):
builder.Services.AddAuthentication(OpenIdConnectDefaults.Authenticat
ionScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureA
d"));
ppsettings.json:
"AzureAd": {
"ClientId": "your-client-id",
"TenantId": "your-tenant-id",
"Instance": "
"CallbackPath": "/signin-oidc"
}
This handles sign-in, token validation, and claims setup automatically.
🔐 11. How to implement Google or Azure AD login?
builder.Services.AddAuthentication()
.AddGoogle(options =>
{
options.ClientId = builder.Configuration["Google:ClientId"];
options.ClientSecret =
builder.Configuration["Google:ClientSecret"];
});
For Azure AD:
builder.Services.AddAuthentication(OpenIdConnectDefaults.Authenticat
ionScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureA
d"));
SP.NET Core will redirect users to Google/Azure login and handle tokens automatically.
🧱 12. What is AuthorizeAttribute?
[Authorize] is an attribute that restricts access to actions or controllers.
Examples:
[Authorize] // Any logged-in user
[Authorize(Roles = "Admin")] // Only admins
[Authorize(Policy = "AdultOnly")] // Custom policy
You can also allow anonymous access:
[AllowAnonymous]
public IActionResult Login() => View();
🧭 13. How to protect specific actions or controllers?
Apply [Authorize] at different levels:
Controller-level:
[Authorize]
public class OrdersController : Controller { ... }
ction-level:
[Authorize(Roles = "Manager")]
public IActionResult ApproveOrder() => View();
⚙ 14. What are authentication schemes?
An authentication scheme defines how users are authenticated — via cookies, JWT,
Google, etc.
Each scheme has:
Example:
builder.Services.AddAuthentication()
.AddCookie("Cookies")
.AddJwtBearer("Jwt", options => { ... });
You can specify the scheme explicitly:
[Authorize(AuthenticationSchemes = "Jwt")]
🔄 15. How to use multiple authentication handlers?
You can configure multiple schemes and choose dynamically per endpoint.
Example:
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "JwtOrCookie";
})
.AddPolicyScheme("JwtOrCookie", "JWT or Cookie", options =>
{
options.ForwardDefaultSelector = context =>
context.Request.Headers.ContainsKey("Authorization") ? "Jwt"
: "Cookies";
})
.AddCookie("Cookies")
.AddJwtBearer("Jwt", options => { ... });
This setup allows both cookie-based (web) and JWT (API) authentication in the same app.
✅ Summary:
Configuration & Environments
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
pp.UseExceptionHandler("/Home/Error");
or
public class GlobalExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
context.Result = new ViewResult { ViewName = "Error" };
}
}
🧩 19. How to return partial views?
Partial views are used to render reusable page sections (like headers, sidebars).
Example:
public IActionResult ProductList()
{
var products = _service.GetAll();
return PartialView("_ProductListPartial", products);
}
In Razor:
@Html.Partial("_ProductListPartial", Model.Products)
🧾 20. Explain Razor Pages vs MVC.
Feature Razor Pages MVC
Structure Page-based (.cshtml +
.cshtml.cs)
Controller + View
Best For Simple or CRUD pages Complex or large web apps
URL /Products/Edit →
/Pages/Products/Edit.cshtml
/Products/Edit →
ProductController.Edit()
Code
Location
In the same file (PageModel) Separate Controller class
Example:
Razor Pages are like simplified MVC without controllers — great for admin dashboards or
forms.
Dependency Injection (DI)
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
builder.Services.AddHealthChecks(); app.MapHealthChecks("/health");
In a production ASP.NET Core MVC application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Application Insights provides monitoring, telemetry, and tracing.
Setup:
builder.Services.AddApplicationInsightsTelemetry(builder.Configurati
on["APPINSIGHTS_INSTRUMENTATIONKEY"]);
Features:
9⃣ How to Monitor Performance and Uptime?
Techniques:
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
TestContainers spins up real Docker containers (SQL Server, Redis) for integration
testing, simulating production.
Example:
using Testcontainers.MsSql;
var sqlContainer = new MsSqlBuilder()
.WithPassword("yourStrong(!)Password")
.Build();
wait sqlContainer.StartAsync();
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlServer(sqlContainer.GetConnectionString())
.Options;
// Use context in tests
✅ Benefits:
Deployment & Hosting
How to Deploy an ASP.NET Core App to IIS?
IIS (Internet Information Services) can host ASP.NET Core apps via the ASP.NET Core
Module, which forwards requests to Kestrel.
Steps:
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
EF Core allows using InMemoryDatabase or mocking DbSet<T> to avoid hitting a real
database.
Example with InMemoryDatabase:
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseInMemoryDatabase(databaseName: "TestDb")
.Options;
using var context = new AppDbContext(options);
context.Products.Add(new Product { Id = 1, Name = "Laptop" });
context.SaveChanges();
// Act
var service = new ProductService(context);
var products = service.GetAll();
// Assert
Assert.Single(products);
Example with Moq (for advanced mocking):
Follow :
var mockSet = new Mock<DbSet<Product>>();
var mockContext = new Mock<AppDbContext>();
mockContext.Setup(c => c.Products).Returns(mockSet.Object);
3⃣ What is Integration Testing in ASP.NET Core?
Integration tests test the application as a whole, including middleware, routing,
controllers, and database.
Example:
public class ProductsApiTests :
IClassFixture<WebApplicationFactory<Program>>
private readonly HttpClient _client;
public ProductsApiTests(WebApplicationFactory<Program> factory)
_client = factory.CreateClient();
[Fact]
public async Task GetProducts_ReturnsOk()
var response = await _client.GetAsync("/api/products");
response.EnsureSuccessStatusCode();
var products = await
response.Content.ReadFromJsonAsync<List<Product>>();
Assert.NotNull(products);
Follow :
✅ Integration tests are slower but catch real runtime issues.
4⃣ How Do You Test Middleware?
Middleware can be tested by invoking it in isolation using RequestDelegate.
Example:
[Fact]
public async Task CustomMiddleware_SetsHeader()
// Arrange
var middleware = new CustomHeaderMiddleware(async
(innerHttpContext) =>
await innerHttpContext.Response.WriteAsync("Hello");
});
var context = new DefaultHttpContext();
// Act
await middleware.InvokeAsync(context);
// Assert
Assert.Equal("MyValue",
context.Response.Headers["X-Custom-Header"]);
✅ Test middleware without starting a real server.
5⃣ How to Use WebApplicationFactory for Testing?
Follow :
WebApplicationFactory<T> spins up your ASP.NET Core app in-memory, perfect for
integration tests or testing minimal APIs.
Example:
var factory = new WebApplicationFactory<Program>();
var client = factory.CreateClient();
var response = await client.GetAsync("/api/products");
response.EnsureSuccessStatusCode();
You can override services for testing:
var factory = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
builder.ConfigureServices(services =>
services.AddDbContext<AppDbContext>(options =>
options.UseInMemoryDatabase("TestDb"));
});
});
6⃣ How to Test Minimal APIs?
Minimal APIs are tested using WebApplicationFactory or TestServer.
Example:
var factory = new WebApplicationFactory<Program>();
var client = factory.CreateClient();
var response = await client.GetAsync("/products");
var products = await
response.Content.ReadFromJsonAsync<List<Product>>();
Follow :
Assert.NotEmpty(products);
7⃣ What Frameworks Are Commonly Used?
Most modern ASP.NET Core projects use xUnit + Moq.
8⃣ How to Use Moq for Mocking Dependencies?
Moq creates fake implementations of interfaces to control behavior during tests.
Example:
var mockRepo = new Mock<IProductRepository>();
mockRepo.Setup(x => x.GetAll()).Returns(new List<Product> { new
Product { Id = 1, Name = "Laptop" } });
var service = new ProductService(mockRepo.Object);
var products = service.GetAll();
Assert.Single(products);
✅ Use .Setup(), .Verify(), and .Returns() to simulate behavior.
9⃣ How to Use InMemoryDatabase for EF Core Testing?
Follow :
EF Core InMemoryDatabase allows quick tests without SQL Server.
Steps:
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Value converters transform data between your entity property and database column type.
Example:
Store an enum as a string in the DB:
modelBuilder.Entity<User>()
.Property(u => u.Status)
.HasConversion<string>();
Or encrypt/decrypt sensitive data:
.Property(p => p.SSN)
.HasConversion(
v => Encrypt(v), // to DB
v => Decrypt(v)); // from DB
🔍 9. What is the Change Tracker?
The Change Tracker keeps track of all entity states (Added, Modified, Deleted,
Unchanged) in a DbContext session.
Example:
var product = _context.Products.Find(1);
product.Price = 1500;
var entries = _context.ChangeTracker.Entries();
foreach (var entry in entries)
Console.WriteLine($"{entry.Entity.GetType().Name} -
{entry.State}");
Follow :
When you call _context.SaveChanges(), EF Core generates the required SQL
automatically.
🔐 10. How does EF Core handle concurrency?
EF Core uses optimistic concurrency — multiple users can edit the same data, but if one
user saves after another, a DbUpdateConcurrencyException occurs.
Example:
Add a concurrency token:
public class Product
public int Id { get; set; }
public string Name { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
EF Core will include RowVersion in the WHERE clause to detect conflicts.
💳 11. How to use transactions in EF Core?
You can use:
using var transaction = _context.Database.BeginTransaction();
try
_context.Add(new Product { Name = "Book" });
_context.SaveChanges();
_context.Add(new Order { ProductId = 1 });
_context.SaveChanges();
Follow :
transaction.Commit();
catch
transaction.Rollback();
Or rely on EF Core’s automatic transaction within a single SaveChanges().
⚡ 12. How do you execute raw SQL in EF Core?
For performance tuning or advanced queries:
var products = _context.Products
.FromSqlRaw("SELECT * FROM Products WHERE Price > 1000")
.ToList();
For non-query operations:
_context.Database.ExecuteSqlRaw("UPDATE Products SET Price = Price *
1.1");
You can also use interpolated strings safely:
.FromSqlInterpolated($"SELECT * FROM Products WHERE Name = {name}");
🕵 13. What are Shadow Properties?
Shadow properties exist in the model but not in your C# class — EF Core creates them
automatically (like CreatedDate or UpdatedBy).
Example:
Follow :
modelBuilder.Entity<Product>()
.Property<DateTime>("CreatedOn")
.HasDefaultValueSql("GETDATE()");
You can access them via the Change Tracker:
var createdOn =
context.Entry(product).Property("CreatedOn").CurrentValue;
🧱 14. What is DbSet<T>?
A DbSet<T> represents a table in the database and provides an API for querying and
saving instances.
Example:
public class AppDbContext : DbContext
public DbSet<Product> Products { get; set; }
Usage:
var allProducts = _context.Products.ToList();
🌱 15. How to seed data in EF Core?
You can seed data via the Fluent API in OnModelCreating.
Example:
modelBuilder.Entity<Category>().HasData(
new Category { Id = 1, Name = "Electronics" },
new Category { Id = 2, Name = "Books" }
Follow :
Then run:
dotnet ef migrations add SeedData
dotnet ef database update
🚀 16. What’s new in EF Core 7/8?
Highlights:
_context.Products.Where(...).ExecuteUpdateAsync()
EF Core 8 is optimized for .NET 8 and cloud-native apps.
⚙ 17. How do you optimize EF Core performance?
Best Practices:
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Partial views are used to render reusable page sections (like headers, sidebars).
Example:
public IActionResult ProductList()
var products = _service.GetAll();
return PartialView("_ProductListPartial", products);
In Razor:
Follow :
@Html.Partial("_ProductListPartial", Model.Products)
🧾 20. Explain Razor Pages vs MVC.
Feature Razor Pages MVC
Structure Page-based (.cshtml +
.cshtml.cs)
Controller + View
Best For Simple or CRUD pages Complex or large web apps
URL /Products/Edit →
/Pages/Products/Edit.cshtml
/Products/Edit →
ProductController.Edit()
Code
Location
In the same file (PageModel) Separate Controller class
Example:
Razor Pages are like simplified MVC without controllers — great for admin dashboards or
forms.
Dependency Injection (DI)
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Using SignalR for Real-Time Communication
// Hub
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message) =>
await Clients.All.SendAsync("ReceiveMessage", user,
message);
}
// Client (JavaScript)
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.build();
connection.on("ReceiveMessage", (user, message) => {
console.log(`${user}: ${message}`);
});
await connection.start();
await connection.invoke("SendMessage", "Alice", "Hello!");ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Logging in production should be:
ASP.NET Core has ILogger interface and supports logging providers like Console, File,
Seq, Application Insights.
Example:
public class HomeController : Controller
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger) => _logger
= logger;
Follow :
public IActionResult Index()
_logger.LogInformation("Index page visited at {Time}",
DateTime.UtcNow);
return View();
6⃣ What is Structured Logging?
Structured logging stores log data as key-value pairs instead of plain text.
Allows querying, filtering, and dashboards.
Example with Serilog:
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.File("logs/log-.txt", rollingInterval:
RollingInterval.Day)
.CreateLogger();
Log Output:
"Timestamp": "2025-10-28T12:00:00Z",
"Level": "Information",
"Message": "Index page visited",
"Time": "2025-10-28T12:00:00Z"
✅ Makes filtering by user, requestId, or error type very easy.
7⃣ How to Use Serilog or NLog?
Follow :
Serilog Example (Program.cs):
builder.Host.UseSerilog((ctx, lc) => lc
.WriteTo.Console()
.WriteTo.File("logs/log-.txt", rollingInterval:
RollingInterval.Day)
NLog Example:
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
You can use:
In a production ASP.NET Core MVC application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
zure App Service PaaS Easy scaling, HTTPS
CI/CD GitHub Actions / Azure DevOps Automated build/test/deploy
Logging ILogger, Serilog, NLog Use structured logging
Monitoring Application Insights, Prometheus Track metrics, uptime
Health Checks ASP.NET Core HealthChecks Expose /health endpoints
This gives a complete production-ready workflow from deployment to monitoring.
dvanced & Modern Topics
Middleware Pipeline in Depth
ASP.NET Core handles HTTP requests through a middleware pipeline, which is a
sequence of components where each can:
Pipeline Flow:
Request -> Middleware1 -> Middleware2 -> Middleware3 -> Endpoint ->
Response back
Example:
pp.Use(async (context, next) =>
{
Console.WriteLine("Before Middleware 1");
wait next();
Console.WriteLine("After Middleware 1");
});
pp.Use(async (context, next) =>
{
Console.WriteLine("Middleware 2");
wait next();
});
pp.Run(async context =>
{
wait context.Response.WriteAsync("Hello World");
});
Key Points:
2⃣ How ASP.NET Core Handles gRPC
builder.Services.AddGrpc();
pp.MapGrpcService<MyGrpcService>();
Use Cases: Microservices, real-time streaming, low-latency APIs.
3⃣ SignalR vs WebSockets
Feature WebSockets SignalR
Protocol Low-level
TCP-based
High-level abstraction
Transpor
Only WebSockets Fallbacks: WebSockets → SSE → Long Polling
Usage Real-time
messages
Real-time hubs with automatic reconnection, grouping,
scaling
✅ Use SignalR for apps needing broadcast, connection management, and fallbacks.
4⃣ Using SignalR for Real-Time Communication
// Hub
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message) =>
wait Clients.All.SendAsync("ReceiveMessage", user,
message);
}
// Client (JavaScript)
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.build();
connection.on("ReceiveMessage", (user, message) => {
console.log(`${user}: ${message}`);
});
wait connection.start();
wait connection.invoke("SendMessage", "Alice", "Hello!");
5⃣ Background Services (IHostedService)
public class TimedWorker : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken
stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
Console.WriteLine("Running background task");
wait Task.Delay(10000, stoppingToken);
}
}
}
builder.Services.AddHostedService<TimedWorker>();
✅ Good for periodic jobs, email processing, queue consumers.
6⃣ Hangfire or Quartz.NET for Background Jobs
Hangfire Example:
pp.UseHangfireDashboard();
RecurringJob.AddOrUpdate(() => Console.WriteLine("Recurring job"),
Cron.Daily);
Quartz.NET: Supports cron-like scheduling and clustered execution.
7⃣ Health Checking in ASP.NET Core
builder.Services.AddHealthChecks()
.AddSqlServer(connectionString)
.AddCheck<CustomHealthCheck>("CustomCheck");
pp.MapHealthChecks("/health");
Custom Health Check Example:
public class CustomHealthCheck : IHealthCheck
{
public Task<HealthCheckResult>
CheckHealthAsync(HealthCheckContext context, CancellationToken
token) =>
Task.FromResult(HealthCheckResult.Healthy("Everything OK"));
}
8⃣ Rate Limiting Middleware in .NET 8
builder.Services.AddRateLimiter(options =>
{
options.GlobalLimiter =
PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>
RateLimitPartition.GetFixedWindowLimiter(httpContext.Connection.Remo
teIpAddress?.ToString()!, _ =>
new FixedWindowRateLimiterOptions
{
PermitLimit = 10,
Window = TimeSpan.FromMinutes(1),
QueueLimit = 2
}));
});
pp.UseRateLimiter();
✅ Helps protect APIs from abuse or DoS attacks.
9⃣ DataAnnotations for Validation
public class Product
{
[Required]
public string Name { get; set; }
[Range(1, 100)]
public decimal Price { get; set; }
}
🔟 Global Exception Logging
pp.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
var error =
context.Features.Get<IExceptionHandlerPathFeature>();
Log.Error(error.Error, "Unhandled exception");
context.Response.StatusCode = 500;
wait context.Response.WriteAsync("An error occurred");
});
});
1⃣1⃣ Anti-Forgery Tokens
<form method="post">
@Html.AntiForgeryToken()
</form>
[ValidateAntiForgeryToken].
1⃣2⃣ Middleware vs Filters vs Handlers
Concept When It Runs Scope Example
Middleware Before/after request Global Logging, authentication
Filters Around controller/action Controller/action Authorization, validation
Handlers Authentication/Authorization Global or
endpoint
JWT handler, Cookie
uth
1⃣3⃣ DI vs Service Locator
Promotes loose coupling.
hidden dependencies, harder to test.
✅ DI is the preferred modern pattern.
Performance Tuning Best Practices
Localization & Globalization
builder.Services.AddLocalization(options => options.ResourcesPath =
"Resources");
var supportedCultures = new[] { "en-US", "fr-FR" };
pp.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("en-US"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
});
✅ Allows apps to support multiple languages & regions.
Output & Input Formatters
builder.Services.AddControllers()
.AddJsonOptions(opt =>
opt.JsonSerializerOptions.PropertyNamingPolicy = null)
.AddXmlSerializerFormatters();
Integrating GraphQL
builder.Services.AddGraphQLServer()
.AddQueryType<Query>();
pp.MapGraphQL();
Common Pitfalls Migrating from MVC 5 to ASP.NET
Core MVC
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Docker allows running ASP.NET Core apps in containers, portable across environments.
Dockerfile Example:
# Build stage
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /app
COPY *.csproj ./
RUN dotnet restore
COPY . ./
RUN dotnet publish -c Release -o out
# Runtime stage
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build /app/out .
ENTRYPOINT ["dotnet", "MyApp.dll"]
Build & Run:
docker build -t myapp:latest .
docker run -d -p 8080:80 myapp:latest
✅ Benefits:
3⃣ How to Host in Azure App Service?
Azure App Service provides PaaS hosting for ASP.NET Core apps.
Steps:
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
public class LogActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext
context)
{
Console.WriteLine($"Action:
{context.ActionDescriptor.DisplayName}");
}
}
Use it:
[LogActionFilter]
public IActionResult Index() => View();
📤 15. How do you pass data from controller to view?
You can use:
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
ASP.NET Core handles HTTP requests through a middleware pipeline, which is a
sequence of components where each can:
Pipeline Flow:
Request -> Middleware1 -> Middleware2 -> Middleware3 -> Endpoint ->
Response back
Example:
app.Use(async (context, next) =>
Console.WriteLine("Before Middleware 1");
await next();
Console.WriteLine("After Middleware 1");
});
app.Use(async (context, next) =>
Console.WriteLine("Middleware 2");
Follow :
await next();
});
app.Run(async context =>
await context.Response.WriteAsync("Hello World");
});
Key Points:
2⃣ How ASP.NET Core Handles gRPC
builder.Services.AddGrpc();
app.MapGrpcService<MyGrpcService>();
Use Cases: Microservices, real-time streaming, low-latency APIs.
3⃣ SignalR vs WebSockets
Follow :
Feature WebSockets SignalR
Protocol Low-level
TCP-based
High-level abstraction
Transpor
Only WebSockets Fallbacks: WebSockets → SSE → Long Polling
Usage Real-time
messages
Real-time hubs with automatic reconnection, grouping,
scaling
✅ Use SignalR for apps needing broadcast, connection management, and fallbacks.
4⃣ Using SignalR for Real-Time Communication
// Hub
public class ChatHub : Hub
public async Task SendMessage(string user, string message) =>
await Clients.All.SendAsync("ReceiveMessage", user,
message);
// Client (JavaScript)
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.build();
connection.on("ReceiveMessage", (user, message) => {
console.log(`${user}: ${message}`);
});
await connection.start();
await connection.invoke("SendMessage", "Alice", "Hello!");
5⃣ Background Services (IHostedService)
Follow :
public class TimedWorker : BackgroundService
protected override async Task ExecuteAsync(CancellationToken
stoppingToken)
while (!stoppingToken.IsCancellationRequested)
Console.WriteLine("Running background task");
await Task.Delay(10000, stoppingToken);
builder.Services.AddHostedService<TimedWorker>();
✅ Good for periodic jobs, email processing, queue consumers.
6⃣ Hangfire or Quartz.NET for Background Jobs
Hangfire Example:
app.UseHangfireDashboard();
RecurringJob.AddOrUpdate(() => Console.WriteLine("Recurring job"),
Cron.Daily);
Quartz.NET: Supports cron-like scheduling and clustered execution.
7⃣ Health Checking in ASP.NET Core
builder.Services.AddHealthChecks()
.AddSqlServer(connectionString)
.AddCheck<CustomHealthCheck>("CustomCheck");
Follow :
app.MapHealthChecks("/health");
Custom Health Check Example:
public class CustomHealthCheck : IHealthCheck
public Task<HealthCheckResult>
CheckHealthAsync(HealthCheckContext context, CancellationToken
token) =>
Task.FromResult(HealthCheckResult.Healthy("Everything OK"));
8⃣ Rate Limiting Middleware in .NET 8
builder.Services.AddRateLimiter(options =>
options.GlobalLimiter =
PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>
RateLimitPartition.GetFixedWindowLimiter(httpContext.Connection.Remo
teIpAddress?.ToString()!, _ =>
new FixedWindowRateLimiterOptions
PermitLimit = 10,
Window = TimeSpan.FromMinutes(1),
QueueLimit = 2
}));
});
app.UseRateLimiter();
✅ Helps protect APIs from abuse or DoS attacks.
Follow :
9⃣ DataAnnotations for Validation
public class Product
[Required]
public string Name { get; set; }
[Range(1, 100)]
public decimal Price { get; set; }
🔟 Global Exception Logging
app.UseExceptionHandler(errorApp =>
errorApp.Run(async context =>
var error =
context.Features.Get<IExceptionHandlerPathFeature>();
Log.Error(error.Error, "Unhandled exception");
context.Response.StatusCode = 500;
await context.Response.WriteAsync("An error occurred");
});
});
1⃣1⃣ Anti-Forgery Tokens
Follow :
<form method="post">
@Html.AntiForgeryToken()
</form>
[ValidateAntiForgeryToken].
1⃣2⃣ Middleware vs Filters vs Handlers
Concept When It Runs Scope Example
Middleware Before/after request Global Logging, authentication
Filters Around controller/action Controller/action Authorization, validation
Handlers Authentication/Authorization Global or
endpoint
JWT handler, Cookie
auth
1⃣3⃣ DI vs Service Locator
Promotes loose coupling.
hidden dependencies, harder to test.
✅ DI is the preferred modern pattern.
Performance Tuning Best Practices
Follow :
Localization & Globalization
builder.Services.AddLocalization(options => options.ResourcesPath =
"Resources");
var supportedCultures = new[] { "en-US", "fr-FR" };
app.UseRequestLocalization(new RequestLocalizationOptions
DefaultRequestCulture = new RequestCulture("en-US"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
});
✅ Allows apps to support multiple languages & regions.
Output & Input Formatters
builder.Services.AddControllers()
.AddJsonOptions(opt =>
opt.JsonSerializerOptions.PropertyNamingPolicy = null)
.AddXmlSerializerFormatters();
Follow :
Integrating GraphQL
builder.Services.AddGraphQLServer()
.AddQueryType<Query>();
app.MapGraphQL();
Common Pitfalls Migrating from MVC 5 to ASP.NET
Core MVC
Follow :
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Docker allows running ASP.NET Core apps in containers, portable across environments.
Dockerfile Example:
# Build stage
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /app
COPY *.csproj ./
RUN dotnet restore
COPY . ./
RUN dotnet publish -c Release -o out
# Runtime stage
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build /app/out .
ENTRYPOINT ["dotnet", "MyApp.dll"]
Build & Run:
docker build -t myapp:latest .
docker run -d -p 8080:80 myapp:latest
✅ Benefits:
3⃣ How to Host in Azure App Service?
Follow :
Azure App Service provides PaaS hosting for ASP.NET Core apps.
Steps:
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Configuration providers are components that load configuration data from various
sources.
Built-in Providers:
Example:
builder.Configuration
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.AddCommandLine(args);
Each provider plugs into the same configuration system, so you can access everything via
IConfiguration.
🔐 3. How do you manage secrets in development?
In development, never store passwords, API keys, or connection strings in code or
ppsettings.json.
Use User Secrets — a safe way to store secrets outside the project tree.
🧰 4. What is User Secrets in ASP.NET Core?
User Secrets are a local, developer-only configuration storage that keeps sensitive data
out of source control.
Setup:
Enable secrets:
dotnet user-secrets init
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
public class LogActionFilter : ActionFilterAttribute
public override void OnActionExecuting(ActionExecutingContext
context)
Console.WriteLine($"Action:
{context.ActionDescriptor.DisplayName}");
Use it:
[LogActionFilter]
public IActionResult Index() => View();
📤 15. How do you pass data from controller to view?
You can use:
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Answer: Hangfire or Quartz.NET for Background Jobs Hangfire Example: app.UseHangfireDashboard(); RecurringJob.AddOrUpdate(() => Console.WriteLine("Recurring job"), Cron.Daily); Quartz.NET: Supports cron-like scheduling and clustered execution.
In a production ASP.NET Core MVC application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
How to Test Minimal APIs?
Answer:
Minimal APIs are tested using WebApplicationFactory or TestServer.
Example:
var factory = new WebApplicationFactory<Program>();
var client = factory.CreateClient();
var response = await client.GetAsync("/products");
var products = await
response.Content.ReadFromJsonAsync<List<Product>>();
Assert.NotEmpty(products);
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Health Checking in ASP.NET Core
builder.Services.AddHealthChecks()
.AddSqlServer(connectionString)
.AddCheck<CustomHealthCheck>("CustomCheck");
app.MapHealthChecks("/health");
Custom Health Check Example:
public class CustomHealthCheck : IHealthCheck
{
public Task<HealthCheckResult>
CheckHealthAsync(HealthCheckContext context, CancellationToken
token) =>
Task.FromResult(HealthCheckResult.Healthy("Everything OK"));
}ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
How to Use Serilog or NLog?
Serilog Example (Program.cs):
builder.Host.UseSerilog((ctx, lc) => lc
.WriteTo.Console()
.WriteTo.File("logs/log-.txt", rollingInterval:
RollingInterval.Day)
);
NLog Example:
builder.Logging.ClearProviders();
builder.Logging.SetMinimumLevel(LogLevel.Information);
builder.Host.UseNLog();
✅ Both support structured logging, sinks, filtering, and rolling files.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
What Frameworks Are Commonly Used?
Answer:
Most modern ASP.NET Core projects use xUnit + Moq.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Compiled queries improve performance by caching query translation.
Example:
private static readonly Func<AppDbContext, decimal,
IEnumerable<Product>> _getExpensiveProducts =
EF.CompileQuery((AppDbContext ctx, decimal price) =>
ctx.Products.Where(p => p.Price > price));
var result = _getExpensiveProducts(_context, 1000);
🔍 19. What is global query filtering?
It allows you to apply filters automatically to all queries for a given entity — useful for soft
deletes or multi-tenancy.
Example:
modelBuilder.Entity<Product>()
.HasQueryFilter(p => !p.IsDeleted);
ll queries automatically exclude deleted products.
🌐 20. How do you handle database connection
pooling?
Connection pooling is handled automatically by ADO.NET and EF Core providers.
Each new DbContext reuses existing connections from the pool to reduce overhead.
For fine control:
options.UseSqlServer(connectionString, opt =>
opt.EnableRetryOnFailure());
Tips:
settings in the connection string:
Max Pool Size=200; Min
Pool Size=5;
uthentication & Authorization