Skip to main content

ASP.NET Core

Overview

ASP.NET Core is Microsoft's modern, cross-platform, high-performance web framework designed for the cloud era.

Supported Workloads

  • Web APIs — RESTful services for mobile and web frontends.
  • MVC Applications — Traditional Server-Side Rendering (SSR).
  • Minimal APIs — High-performance, low-ceremony microservices.
  • Real-time Apps — Powered by SignalR.
  • gRPC Services — Contract-first, high-performance RPC.
  • Blazor — Interactive web UIs using C# instead of JavaScript.

Platform Compatibility

PlatformSupported
Windows
Linux
macOS
Docker
Kubernetes

Why Choose ASP.NET Core?

The framework consistently ranks as one of the fastest web frameworks in the TechEmpower Benchmarks. Its modular design allows you to include only the dependencies you need.

FeatureTechnical Benefit
Cross-platformDevelop on macOS/Windows; deploy on Linux containers.
High PerformanceOptimized Kestrel server and non-blocking I/O.
Built-in DINative Dependency Injection for cleaner, testable code.
Middleware PipelineFull control over the HTTP request/response lifecycle.
Cloud NativeBuilt-in support for health checks, logging, and configuration.
Unified FrameworkOne programming model for both Web UI and Web APIs.

System Architecture

The request flow in ASP.NET Core follows a "Russian Doll" model where requests pass through a series of components (Middleware) before reaching your logic.


Core Concepts to Master

Cloud-Ready Design

To build "Cloud-Ready" apps, focus on the Stateless principle. Avoid in-memory sessions; use distributed caches like Redis and external identity providers.

  1. Dependency Injection (DI): Understanding Transient, Scoped, and Singleton lifetimes is critical for resource management.
  2. Configuration: Utilizing appsettings.json, Environment Variables, and Secret Manager.
  3. Entity Framework Core: The standard Object-Relational Mapper (ORM) for data access.
  4. Logging: Built-in support for providers like Serilog or Azure Application Insights.

Kestrel Web Server

ASP.NET Core uses Kestrel as its default web server.

Responsibilities:

  • HTTP request handling
  • HTTPS support
  • High-performance networking
  • Async processing

Middleware Pipeline

Middleware components process HTTP requests sequentially.

Example Middleware

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.Use(async (context, next) =>
{
Console.WriteLine("Before Request");

await next();

Console.WriteLine("After Response");
});

app.Run();

Project Structure

MyAspNetApp/

├── Controllers/
├── Models/
├── Services/
├── Repositories/
├── Middleware/
├── Data/
├── DTOs/
├── appsettings.json
├── Program.cs
└── MyAspNetApp.csproj

Hosting Model

Program.cs (.NET 6+)

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

var app = builder.Build();

app.MapControllers();

app.Run();

Dependency Injection (DI)

Service Lifetimes

LifetimeDescription
SingletonOne instance for app lifetime
ScopedOne per HTTP request
TransientNew instance every time

Registering Services

builder.Services.AddScoped<IUserService, UserService>();

Constructor Injection

public class UserController : ControllerBase
{
private readonly IUserService _service;

public UserController(IUserService service)
{
_service = service;
}
}

Routing

Attribute Routing

[ApiController]
[Route("api/users")]
public class UsersController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok();
}
}

Route Parameters

[HttpGet("{id}")]
public IActionResult GetById(int id)
{
return Ok(id);
}

Controllers & APIs

[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetProducts()
{
return Ok(new[] { "Laptop", "Mouse" });
}
}

Minimal APIs

Minimal APIs reduce boilerplate.

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.MapGet("/", () => "Hello ASP.NET Core");

app.Run();

Model Binding

Model binding converts HTTP data into C# objects.

public class CreateUserRequest
{
public string Name { get; set; }
}

[HttpPost]
public IActionResult Create(CreateUserRequest request)
{
return Ok(request.Name);
}

Validation

public class RegisterRequest
{
[Required]
[EmailAddress]
public string Email { get; set; }
}

Entity Framework Core Integration

builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("Default")));

Configuration System

Configuration supports:

  • appsettings.json
  • Environment variables
  • Azure Key Vault
  • Command-line args
  • Secrets Manager
{
"ConnectionStrings": {
"Default": "Server=.;Database=ShopDb;"
}
}

Logging

private readonly ILogger<UserService> _logger;

_logger.LogInformation("User created");

Authentication

Authentication TypeSupported
JWT
Cookies
OAuth2
OpenID Connect
Identity Server

JWT Authentication

builder.Services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "https://localhost:5001";
options.Audience = "api";
});

Authorization

[Authorize(Roles = "Admin")]
public IActionResult AdminOnly()
{
return Ok();
}

Exception Handling

app.UseExceptionHandler("/error");

Middleware Ordering

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

Swagger / OpenAPI

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

app.UseSwagger();
app.UseSwaggerUI();

CORS

builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll",
policy =>
{
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});

Background Services

public class Worker : BackgroundService
{
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(1000);
}
}
}

Real-Time Communication with SignalR

public class ChatHub : Hub
{
public async Task Send(string message)
{
await Clients.All.SendAsync("Receive", message);
}
}

gRPC in ASP.NET Core

Use cases:

  • Microservices
  • Internal APIs
  • High-throughput systems

Performance Optimization

OptimizationBenefit
Async/AwaitNon-blocking I/O
Response CachingFaster responses
CompressionReduced bandwidth
Connection PoolingBetter DB performance
Minimal APIsLower overhead
[HttpGet]
public async Task<IActionResult> Get()
{
var users = await _service.GetUsersAsync();
return Ok(users);
}

Security Best Practices

Security FeaturePurpose
HTTPSEncrypt traffic
JWT ValidationSecure authentication
Input ValidationPrevent injection
Rate LimitingPrevent abuse
CORSRestrict origins
Secret ManagerProtect secrets

Common Pitfalls

MistakeProblem
Blocking async callsThread starvation
Incorrect middleware orderBroken auth
Large controllersPoor maintainability
Missing validationInvalid data
Exposing secretsSecurity risk

Testing ASP.NET Core

[Fact]
public void Should_Return_User()
{
Assert.NotNull(user);
}

Integration testing with:

  • TestServer
  • WebApplicationFactory
  • In-memory hosting

Clean Architecture

src/

├── Api/
├── Application/
├── Domain/
├── Infrastructure/
└── Tests/

Advanced Topics

TopicDescription
Endpoint FiltersRequest interception
Rate LimitingTraffic control
Output CachingFaster APIs
API VersioningBackward compatibility
Health ChecksService monitoring
OpenTelemetryObservability
builder.Services.AddHealthChecks();
app.MapHealthChecks("/health");

Deployment

PlatformSupported
IIS
Docker
Kubernetes
Azure App Service
Linux Nginx
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY . .
ENTRYPOINT ["dotnet", "MyApp.dll"]

Interview Questions

Beginner

  1. What is ASP.NET Core?
  2. What is middleware?
  3. Difference between MVC and Minimal APIs?
  4. What is dependency injection?
  5. Explain service lifetimes.

Intermediate

  1. How authentication works?
  2. Explain middleware ordering.
  3. Difference between scoped and singleton?
  4. What is model binding?
  5. How does routing work?

Advanced

  1. Explain request pipeline internals.
  2. How would you scale ASP.NET Core?
  3. Explain Kestrel architecture.
  4. What causes thread starvation?
  5. How would you implement CQRS?

Cheat Sheet

TaskCode
Add Controllersbuilder.Services.AddControllers()
Map Controllersapp.MapControllers()
Enable SwaggerAddSwaggerGen()
Register DIAddScoped<T>()
Enable CORSAddCors()
Add AuthAddAuthentication()

Learning Roadmap