This .NET Core interview preparation guide focuses on understanding each concept, explaining when it matters, and supporting your answer with a practical example. Use it as a revision checklist and practise explaining the ideas in your own words.
1. What is .NET Core, and how does it relate to modern .NET?
Answer: .NET Core was the cross-platform, open-source implementation line introduced for modern .NET applications. Starting with .NET 5, Microsoft dropped the “Core” part of the product name and continued the unified platform as .NET. Many interviewers still say .NET Core to refer to ASP.NET Core and the modern cross-platform stack. When discussing a project, mention its actual target framework, such as net8.0 or net10.0.
Example
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
2. What is dependency injection in ASP.NET Core?
Answer: Dependency injection (DI) supplies a class with the services it needs instead of having the class construct concrete dependencies itself. ASP.NET Core includes a built-in service container. Register interfaces and implementations during startup, then request the dependency through a constructor. DI improves testability, supports replaceable implementations and makes object lifetimes explicit.
Example
builder.Services.AddScoped();
public class OrdersController(IOrderService orders) : ControllerBase
{
// Use orders without constructing OrderService here.
}
3. Explain Singleton, Scoped and Transient service lifetimes.
Answer: Singleton creates one instance for the application service provider and reuses it. Scoped creates one instance per scope; in a typical web request, that is one instance per request. Transient creates a new instance each time it is requested. A common mistake is injecting a scoped service such as DbContext into a singleton, which can cause lifetime and concurrency problems. Choose a lifetime based on state and resource ownership.
Example
builder.Services.AddSingleton();
builder.Services.AddScoped();
builder.Services.AddTransient();
4. What is middleware in ASP.NET Core?
Answer: Middleware is a component in the HTTP request pipeline. Each component can inspect or modify the request, call the next component, and then inspect or modify the response. Middleware can also short-circuit the pipeline. Ordering matters: exception handling should be early, routing must run before endpoint-specific authorization, and authentication should normally run before authorization.
Example
app.UseExceptionHandler();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
5. What is the difference between Use, Run and Map in the middleware pipeline?
Answer: Use adds middleware that can call the next delegate. Run adds terminal middleware that does not call the next delegate, so it ends the pipeline for matching requests. Map branches the pipeline based on a path prefix. Use these methods to compose small request-processing behaviours; in typical applications, framework extensions such as UseRouting and UseAuthentication are more common.
Example
app.Use(async (context, next) => {
await next();
});
app.Map("/health-text", branch =>
branch.Run(ctx => ctx.Response.WriteAsync("healthy")));
6. What is the difference between authentication and authorization?
Answer: Authentication establishes who the caller is. Authorization determines what the authenticated caller is allowed to do. ASP.NET Core authentication handlers validate credentials and create a ClaimsPrincipal; authorization policies, roles and requirements evaluate access. A user can be authenticated but still receive a 403 Forbidden response because they lack permission.
Example
builder.Services.AddAuthorization(options =>
options.AddPolicy("CanManageOrders", p => p.RequireClaim("permission", "orders.manage")));
[Authorize(Policy = "CanManageOrders")]
[HttpDelete("{id:int}")]
public IActionResult Delete(int id) => NoContent();
7. How does configuration work in ASP.NET Core?
Answer: The configuration system combines providers such as JSON files, environment variables, command-line arguments and secret stores. Later providers can override earlier values. Applications normally use strongly typed options classes rather than scattering string-based configuration reads throughout the code. Secrets should not be committed to source control; use development user secrets and a secure production secret store or environment configuration.
Example
var connection = builder.Configuration.GetConnectionString("MainDb");
public sealed class MailOptions { public string From { get; set; } = ""; }
builder.Services.Configure<MailOptions>(builder.Configuration.GetSection("Mail"));
8. What is the Options pattern?
Answer: The Options pattern binds a configuration section to a strongly typed class and makes configuration easier to validate and consume through DI. IOptions<T> is a simple snapshot of configured options, IOptionsSnapshot<T> is scoped and can be refreshed per request, and IOptionsMonitor<T> supports change notifications and reading current values. The appropriate interface depends on whether the value needs to update while the app runs.
Example
builder.Services.AddOptions<MailOptions>()
.Bind(builder.Configuration.GetSection("Mail"))
.Validate(o => !string.IsNullOrWhiteSpace(o.From), "Mail:From is required");
9. What is Kestrel?
Answer: Kestrel is the cross-platform web server used by ASP.NET Core. It listens for HTTP requests and forwards them into the ASP.NET Core request pipeline. It can run directly at the edge or behind a reverse proxy such as IIS, Nginx or a cloud load balancer. In a reverse-proxy deployment, forwarded headers and trusted-proxy configuration should be handled correctly so the app sees the original scheme and client information.
Example
A typical deployment can terminate public HTTPS at a reverse proxy and forward traffic to Kestrel on an internal endpoint.
10. What is the difference between MVC controllers and Minimal APIs?
Answer: Controller-based APIs use controllers, action methods, attributes, filters and model-binding conventions. Minimal APIs define endpoints directly with route mapping and concise handlers. Both run on ASP.NET Core and can use DI, authentication, validation and OpenAPI support. Choose controllers when an application benefits from controller conventions and organisation; choose Minimal APIs for small services or compact endpoint definitions.
Example
app.MapGet("/api/orders/{id:int}", async (int id, IOrderService service) =>
await service.GetAsync(id));
[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase { }
11. What is model binding and model validation?
Answer: Model binding maps values from route data, query strings, headers and request bodies to action parameters or model properties. Validation checks whether the resulting model satisfies rules such as required fields or ranges. With [ApiController], invalid model state normally produces an automatic 400 response. For complex business rules, use application-level validation as well as simple input annotations.
Example
public record CreateCustomerRequest(
[Required] string Name,
[EmailAddress] string Email);
[HttpPost]
public IActionResult Create(CreateCustomerRequest request) => Ok();
12. How do you implement JWT bearer authentication?
Answer: A JWT bearer handler reads the Authorization header, validates the token signature, issuer, audience and lifetime, and creates a user principal from its claims. The API should validate tokens using trusted keys and configuration; it should not simply decode a token and trust its contents. Keep signing keys secure, use HTTPS, and make token lifetime and refresh design appropriate to the application.
Example
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options => {
options.Authority = builder.Configuration["Auth:Authority"];
options.Audience = builder.Configuration["Auth:Audience"];
});
13. What is CORS and why is it needed?
Answer: Cross-Origin Resource Sharing is a browser security mechanism that lets a server state which origins may access its resources through browser requests. Configure explicit trusted origins, methods and headers. Do not combine wildcard origins with credentials. CORS is enforced by browsers; it is not an authentication system and does not stop non-browser clients from calling the API.
Example
builder.Services.AddCors(options => options.AddPolicy("Frontend", policy =>
policy.WithOrigins("https://app.example.com")
.AllowAnyHeader().AllowAnyMethod()));
app.UseCors("Frontend");
14. How do you handle global exceptions in ASP.NET Core?
Answer: Use central exception-handling middleware to catch unhandled exceptions, log them with correlation information and return a consistent error response. Do not expose stack traces or database details to clients in production. For APIs, Problem Details provides a standard response shape. Handle expected validation and not-found outcomes explicitly instead of treating every business outcome as an unhandled exception.
Example
builder.Services.AddProblemDetails();
app.UseExceptionHandler(); // Configure early in the pipeline
15. What is the difference between middleware and action filters?
Answer: Middleware runs in the HTTP pipeline and can apply to requests before routing or across many endpoints. MVC filters run within the MVC action execution pipeline and have access to action-specific context such as action arguments and model state. Use middleware for cross-cutting HTTP concerns such as exception handling or request logging; use filters for MVC-specific concerns such as action execution policies.
Example
A request correlation middleware can run for every request, while an action filter can validate metadata specific to controller actions.
16. How should logging be implemented in ASP.NET Core?
Answer: Use the built-in ILogger abstraction and structured logging rather than writing directly to the console throughout the application. Log useful context such as order IDs and correlation IDs, but do not log passwords, access tokens or sensitive personal information. Configure providers and log levels per environment. Use scopes to attach common properties to a group of log messages.
Example
public class OrderService(ILogger<OrderService> logger)
{
public void Process(int orderId) =>
logger.LogInformation("Processing order {OrderId}", orderId);
}
17. What is a hosted service or BackgroundService?
Answer: A hosted service is a long-running background task managed by the ASP.NET Core host. Derive from BackgroundService and implement ExecuteAsync for a worker loop. Respect the cancellation token during delays and I/O. If the worker needs scoped services, create a scope with IServiceScopeFactory instead of injecting a scoped dependency directly into the singleton hosted service.
Example
public sealed class CleanupWorker(ILogger<CleanupWorker> log) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
log.LogInformation("Cleanup check running");
await Task.Delay(TimeSpan.FromMinutes(5), token);
}
}
}
18. How do you improve performance in an ASP.NET Core application?
Answer: Start by measuring with logs, traces and profiling rather than guessing. Common improvements include asynchronous I/O, database query optimisation, pagination, response compression, caching suitable read-heavy data, reducing unnecessary allocations and avoiding blocking calls. Use output caching or distributed caching only when the data and invalidation rules are understood. Validate performance under realistic concurrency and payload sizes.
Example
For a read endpoint, project only required columns and apply pagination instead of loading every database row into memory.
19. What are health checks in ASP.NET Core?
Answer: Health checks expose whether an application and its dependencies are functioning. A liveness check indicates whether the process should be restarted; a readiness check indicates whether it can receive traffic. Check dependencies such as databases or queues for readiness, but keep endpoints protected or expose only the information needed by the infrastructure. Avoid expensive checks on every probe.
Example
builder.Services.AddHealthChecks();
app.MapHealthChecks("/health");
20. What is the difference between in-memory cache and distributed cache?
Answer: An in-memory cache stores values inside one application process. It is fast, but each server instance has its own cache and data is lost when the process restarts. A distributed cache, such as Redis, is shared by multiple application instances and is useful in scaled deployments. Decide expiration and invalidation rules carefully; caching stale or sensitive data can create correctness and security problems.
Example
builder.Services.AddMemoryCache();
// For multiple instances, configure a shared IDistributedCache provider.
How to prepare for your interview
Do not memorise definitions word for word. Practise explaining the concept in your own words, describe when you would use it, and mention one trade-off or common mistake. For coding and database topics, write the example yourself and test the edge cases.
Use this guide as a revision checklist, then review the topics you find difficult in more depth. Interview discussions often move from fundamentals to project decisions, debugging and performance scenarios.
Keep learning with DotNetRevision. Explore the ebook library for structured study guides, interview preparation and practical professional-development resources.