Website Backend Development with C# (.NET / ASP.NET Core)
ASP.NET Core is a mature platform with predictable behavior under load, strict typing, and a vast NuGet ecosystem. It's chosen when your team already has .NET engineers, when integration with Active Directory/Azure AD is needed, or when performance requirements are too demanding for Node.js.
When .NET is justified
If the API needs to handle thousands of requests per second with synchronous database operations — ASP.NET Core on Kestrel without a reverse proxy easily holds 50–80k RPS on a single core. If the project already uses C# in the frontend (Blazor) or desktop part — a monorepo with a single language reduces overhead. If you need built-in DI, OpenAPI, gRPC, and WebSocket without six separate libraries.
Project structure
Minimal API on .NET 8 without controllers:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<AppDbContext>(opt =>
opt.UseNpgsql(builder.Configuration.GetConnectionString("Default")));
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(opt =>
{
opt.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidateAudience = false,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Secret"]!))
};
});
var app = builder.Build();
app.MapGet("/users/{id:int}", async (int id, IUserService svc) =>
await svc.GetByIdAsync(id) is { } user
? Results.Ok(user)
: Results.NotFound());
app.MapPost("/users", async (CreateUserDto dto, IUserService svc) =>
{
var user = await svc.CreateAsync(dto);
return Results.Created($"/users/{user.Id}", user);
});
app.Run();
For projects more complex than three entities, separate layers are better: Domain, Application, Infrastructure, WebApi. Vertical Slice Architecture with MediatR is a good alternative to classical layering:
// Features/Users/GetUser.cs
public static class GetUser
{
public record Query(int Id) : IRequest<UserDto?>;
public class Handler(AppDbContext db) : IRequestHandler<Query, UserDto?>
{
public async Task<UserDto?> Handle(Query req, CancellationToken ct) =>
await db.Users
.Where(u => u.Id == req.Id)
.Select(u => new UserDto(u.Id, u.Email, u.CreatedAt))
.FirstOrDefaultAsync(ct);
}
}
Entity Framework Core vs Dapper
EF Core with migrations is standard for CRUD-heavy services. Dapper is used for reporting queries where ORM generates suboptimal SQL.
// EF Core — automatic migrations
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public DbSet<User> Users => Set<User>();
protected override void OnModelCreating(ModelBuilder mb)
{
mb.Entity<User>(e =>
{
e.HasIndex(u => u.Email).IsUnique();
e.Property(u => u.CreatedAt).HasDefaultValueSql("now()");
});
}
}
// Dapper — when you need raw SQL
public async Task<IEnumerable<ReportRow>> GetReportAsync(DateRange range)
{
await using var conn = new NpgsqlConnection(_connStr);
return await conn.QueryAsync<ReportRow>("""
SELECT date_trunc('day', created_at) AS day,
count(*) AS orders,
sum(total) AS revenue
FROM orders
WHERE created_at BETWEEN @From AND @To
GROUP BY 1
ORDER BY 1
""", new { range.From, range.To });
}
Caching and background tasks
Output Cache on .NET 8 — declarative response caching directly on the endpoint:
builder.Services.AddOutputCache(opt =>
{
opt.AddPolicy("products", p => p.Expire(TimeSpan.FromMinutes(10)).Tag("products"));
});
app.MapGet("/products", async (IProductRepo repo) => await repo.GetAllAsync())
.CacheOutput("products");
// Invalidation after changes
app.MapPost("/products", async (CreateProductDto dto, IOutputCacheStore cache, ...) =>
{
var product = await svc.CreateAsync(dto);
await cache.EvictByTagAsync("products", CancellationToken.None);
return Results.Created($"/products/{product.Id}", product);
});
Background tasks via IHostedService or Hangfire:
// Simple background task
public class EmailWorker(IServiceProvider sp) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
using var scope = sp.CreateScope();
var queue = scope.ServiceProvider.GetRequiredService<IEmailQueue>();
var mailer = scope.ServiceProvider.GetRequiredService<IMailer>();
await foreach (var msg in queue.DequeueAsync(ct))
await mailer.SendAsync(msg, ct);
}
}
}
SignalR for real-time
public class NotificationHub : Hub
{
public async Task JoinGroup(string groupName) =>
await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
}
// Sending from service
public class OrderService(IHubContext<NotificationHub> hub)
{
public async Task UpdateStatusAsync(int orderId, string status)
{
await _db.Orders.Where(o => o.Id == orderId)
.ExecuteUpdateAsync(s => s.SetProperty(o => o.Status, status));
await hub.Clients.Group($"order-{orderId}")
.SendAsync("StatusChanged", new { orderId, status });
}
}
Deployment
Dockerfile for production:
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY ["MyApi.csproj", "."]
RUN dotnet restore
COPY . .
RUN dotnet publish -c Release -o /app/publish
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS runtime
WORKDIR /app
COPY --from=build /app/publish .
ENV ASPNETCORE_URLS=http://+:8080
ENV ASPNETCORE_ENVIRONMENT=Production
EXPOSE 8080
ENTRYPOINT ["dotnet", "MyApi.dll"]
Health checks for orchestrators:
builder.Services.AddHealthChecks()
.AddNpgsql(connStr, name: "postgres")
.AddRedis(redisConn, name: "redis");
app.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = _ => false });
app.MapHealthChecks("/health/ready");
Timeline
Simple REST API (5–10 endpoints, one database, JWT authentication): 5–8 working days. Full-fledged backend with roles, background tasks, WebSocket, integration testing and CI/CD: 3–5 weeks. Migration of an existing .NET Framework project to .NET 8 depends on legacy depth — estimate separately after codebase audit.







