โฐ Tasks That Run Forever Need to process queue every minute? Send emails in background? Background Services run continuously alongside your ASP.NET app. Perfect for scheduled tasks, workers. Create Background Service public class EmailProcessorService : BackgroundService { private readonly ILogger _logger; private readonly IServiceProvider _serviceProvider; public EmailProcessorService( ILogger logger, IServiceProvider serviceProvider) { _logger = logger; […]
Category: Asp.Net Core
.NET Core: Use Minimal APIs for Lightweight HTTP Services
๐ APIs in 10 Lines of Code MVC Controllers for simple API? Overkill. Minimal APIs (.NET 6+) create HTTP endpoints with minimal ceremony. Perfect for microservices, simple APIs. Traditional Controller vs Minimal API // โ Traditional Controller (verbose) [ApiController] [Route(“api/[controller]”)] public class UsersController : ControllerBase { private readonly IUserService _userService; public UsersController(IUserService userService) { _userService […]
.NET Core: Add Health Checks to Monitor Application Status
๐ Know When Your App Is Sick Load balancer needs to know: is app healthy? Database connected? Redis available? Health checks provide instant status. Basic Health Check Setup // Program.cs var builder = WebApplication.CreateBuilder(args); // Add health checks builder.Services.AddHealthChecks(); var app = builder.Build(); // Map health check endpoint app.MapHealthChecks(“/health”); app.Run(); // GET /health // Response: […]
.NET Core: Use IHostedService for Background Tasks
โฐ Long-Running Tasks in ASP.NET Core Need scheduled jobs? Background processing? Email queue? IHostedService runs tasks in background without blocking requests. Basic Background Service public class EmailQueueService : BackgroundService { private readonly ILogger _logger; private readonly IServiceProvider _services; public EmailQueueService( ILogger logger, IServiceProvider services) { _logger = logger; _services = services; } protected override async […]
.NET Core: Use Result Pattern Instead of Throwing Exceptions
๐ฏ Explicit Error Handling Exceptions for control flow? Expensive. Hidden. Result pattern makes errors explicit and performant. Traditional Exception Way public User GetUser(int id) { var user = _db.Users.Find(id); if (user == null) throw new NotFoundException(“User not found”); if (!user.IsActive) throw new InvalidOperationException(“User inactive”); return user; } // Caller has no idea what exceptions to […]
.NET Core: Use Minimal APIs for Lightweight Endpoints
โก Build APIs in 5 Lines of Code Skip controllers, routing, Startup.cs. Minimal APIs (.NET 6+) make simple endpoints incredibly simple. Traditional Controller Way // Startup.cs public void ConfigureServices(IServiceCollection services) { services.AddControllers(); } public void Configure(IApplicationBuilder app) { app.UseRouting(); app.UseEndpoints(endpoints => endpoints.MapControllers()); } // UsersController.cs [ApiController] [Route(“api/[controller]”)] public class UsersController : ControllerBase { [HttpGet] public […]
.NET Core: Use Health Checks for Monitoring
How do you know if your API is healthy? Database connected? Redis alive? // Program.cs builder.Services.AddHealthChecks() .AddDbContextCheck() .AddRedis(“localhost:6379”); app.MapHealthChecks(“/health”); // Visit /health // Response: Healthy or Unhealthy + details Custom Check: public class ApiHealthCheck : IHealthCheck { public async Task CheckHealthAsync(…) { var isHealthy = await CheckExternalApiAsync(); return isHealthy ? HealthCheckResult.Healthy() : HealthCheckResult.Unhealthy(“API down”); } […]
.NET Core: Use Response Caching Middleware for Static APIs
API returns same data for 10 minutes. Still hitting database every request. // Program.cs builder.Services.AddResponseCaching(); var app = builder.Build(); app.UseResponseCaching(); // Controller [ResponseCache(Duration = 600)] // 10 minutes public IActionResult GetProducts() { return Ok(_db.Products.ToList()); } Headers: Sets Cache-Control headers automatically. Browser + server cache. Vary: Cache different responses per user: VaryByHeader = “Authorization” Disable: [ResponseCache(NoStore […]
.NET Core: Use IHostedService for Startup/Shutdown Logic
๐ฌ Lifecycle Hooks Run code on app start/stop. Warm cache, close connections cleanly. public class StartupService : IHostedService { public async Task StartAsync(CancellationToken cancellationToken) { // Runs when app starts await WarmCacheAsync(); await CheckDatabaseConnectionAsync(); } public async Task StopAsync(CancellationToken cancellationToken) { // Runs when app stops (graceful shutdown) await FlushLogsAsync(); await CloseConnectionsAsync(); } } // […]
.NET Core: Use IMemoryCache for In-Memory Caching Without Redis
โก Built-in Cache Redis overkill for small apps. IMemoryCache built into .NET. Zero config. // Startup services.AddMemoryCache(); // Usage public class UserService { private readonly IMemoryCache _cache; public async Task GetUserAsync(int id) { return await _cache.GetOrCreateAsync( $”user-{id}”, async entry => { entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5); return await _db.Users.FindAsync(id); } ); } } When It’s Enough: Single […]
.NET Core: Handling Errors Gracefully with Middleware
Stop using try-catch in every Controller action. It’s messy. Use a Global Exception Middleware. app.UseExceptionHandler(exceptionHandlerApp => { exceptionHandlerApp.Run(async context => { // Log the error and return a professional JSON response }); }); This keeps your code dry and ensures your users never see a ‘Yellow Screen of Death’.
.NET Core: Mastering Service Lifetimes (A Visual Guide)
๐น Transient: New instance every time. ๐น Scoped: One instance per HTTP request. ๐น Singleton: One instance for the entire app life. Using a Scoped service inside a Singleton will cause major memory leaks! Always double-check your DI graph.
.NET Core: Architecting Scalable Services with Minimal APIs
Minimal APIs are not just for ‘small’ apps. They offer less overhead than Controllers by avoiding the MVC filter pipeline where it’s not needed. app.MapGet(“/user/{id}”, async (int id, IUserService service) => await service.GetById(id)) .WithName(“GetUser”) .WithOpenApi(); Senior Tip: Use ‘Endpoint Filters’ to handle cross-cutting concerns like validation and logging without the complexity of traditional Action Filters.
.NET Core: High-Performance Code with C# Source Generators
Reflection is slow. Source Generators allow you to generate C# code during compilation based on your existing code, moving logic from runtime to compile time. Pro Use Case: Automatically generating mapping code (like AutoMapper but zero runtime cost) or creating strongly-typed API clients. This is how modern .NET achieves world-class performance.
.NET Core: Native Rate Limiting – Shielding Your API from Abuse
No more 3rd party libraries. .NET 7+ has built-in Rate Limiting. Protect your endpoints from DDoS or brute force in 3 lines of code. app.UseRateLimiter(new FixedWindowRateLimiterOptions { PermitLimit = 10, Window = TimeSpan.FromSeconds(1) });
.NET Core: Streaming Large Data with IAsyncEnumerable
Loading 100,000 rows into a List<T> before sending it to the client will spike your RAM. Use IAsyncEnumerable to stream data. public async IAsyncEnumerable GetUsersStream() { foreach (var user in _db.Users) { yield return await Process(user); } } The Result: The client starts receiving data immediately, and your server’s memory usage stays flat regardless of […]
.NET Core: Scaling with Redis and IDistributedCache
In-memory cache fails when you have multiple server instances. Use Distributed Caching to share data across your entire cluster. // In Program.cs builder.Services.AddStackExchangeRedisCache(options => { options.Configuration = “localhost:6379”; }); Now, when Server A caches a user’s session, Server B can access it immediately, ensuring a seamless user experience in a load-balanced environment.
.NET Core: Zero-Startup Latency with Native AOT Compilation
Modern cloud apps need to start fast (Cold Starts). Native AOT compiles your C# directly to machine code, removing the need for the JIT compiler at runtime. Benefits: Smaller binary size, lower memory footprint, and near-instant startup. Perfect for AWS Lambda or Azure Functions where you pay for every millisecond of execution.
.NET Core: Reducing Data Transfer Costs with Response Compression
Sending large JSON payloads? Compress them with Brotli or Gzip automatically at the middleware level. builder.Services.AddResponseCompression(options => { options.EnableForHttps = true; }); app.UseResponseCompression(); The Impact: Reduces payload size by up to 70%, making your mobile app much faster on slow 4G networks.
.NET Core: Implementing Professional Monitoring with Health Checks
How does your load balancer know your app is healthy? Not just ‘running’, but actually connected to the DB. // In Program.cs builder.Services.AddHealthChecks() .AddSqlServer(builder.Configuration.GetConnectionString(“Default”)); app.MapHealthChecks(“/health”); The Benefit: It returns a 200 OK only if the app AND its dependencies are healthy. Essential for Kubernetes deployments.
.NET Core: Implementing a Global Exception Handler for Clean Controllers
Stop putting try-catch blocks in every controller action. Use the built-in UseExceptionHandler middleware. app.UseExceptionHandler(errorApp => { errorApp.Run(async context => { context.Response.StatusCode = 500; await context.Response.WriteAsJsonAsync(new { Message = “Server Error” }); }); });
.NET Core: Preventing ‘Captive Dependency’ Memory Leaks
A captive dependency occurs when a Singleton service depends on a Scoped service. The Risk: The Scoped service will stay in memory as long as the Singleton lives, causing potential memory leaks or stale data. Pro Tip: Always use IServiceScopeFactory inside singletons to resolve scoped services manually when needed.
.NET Core Background Services: Running Tasks Without Blocking Your API
โฐ The Slow Endpoint Problem User uploads 100MB file. Your API processes it… for 45 seconds. Request times out. User refreshes. Uploads again. Your server? On fire. ๐ฅ Background Services: The Fire-and-Forget Pattern โ Blocking the Request (Bad) [HttpPost(“upload”)] public async Task Upload(IFormFile file) { // Save file await SaveFileAsync(file); // 2 seconds // Generate […]
.NET Core Middleware: Building a Production-Grade Request Pipeline
๐ The Request Pipeline Mystery Your API is slow. Users complain. You add logging… but where? You need auth checks, rate limiting, error handling. They’re scattered everywhere. Sound chaotic? Understanding the Middleware Pipeline ๐ฏ What Middleware Actually Does Request comes in โ โโ Logging Middleware (start timer) โ โโ Auth Middleware (check JWT) โ โ […]
.NET Core: Use HttpClientFactory to Prevent Socket Exhaustion
Creating new HttpClient instances exhausts sockets. HttpClientFactory manages client lifecycle properly. โ Wrong: using var client = new HttpClient(); // Socket exhaustion! var response = await client.GetAsync(url); โ Right: // Program.cs builder.Services.AddHttpClient(“MyAPI”, client => { client.BaseAddress = new Uri(“https://api.example.com”); }); // Service public class MyService { private readonly IHttpClientFactory _factory; public MyService(IHttpClientFactory factory) { _factory […]
.NET Core: Use ActionFilters for Cross-Cutting Concerns
Logging, validation, auth in every controller is repetitive. ActionFilters apply logic globally or per-controller. Create Filter: public class LoggingFilter : IActionFilter { public void OnActionExecuting(ActionExecutingContext context) { // Before action Console.WriteLine($”Executing: {context.ActionDescriptor.DisplayName}”); } public void OnActionExecuted(ActionExecutedContext context) { // After action Console.WriteLine($”Executed: {context.ActionDescriptor.DisplayName}”); } } Apply Globally: builder.Services.AddControllers(options => { options.Filters.Add(); }); Or apply to […]
.NET Core: High Performance Microservices with Minimal APIs
Controllers add overhead. For high-speed microservices, use Minimal APIs. They are faster, use less memory, and are perfect for serverless deployments. app.MapGet(“/order/{id}”, (int id) => new Order(id));
.NET Core: Implementing Clean Architecture for Enterprise Apps
Architecture is about separating concerns. In Clean Architecture, the Domain (Logic) is at the center, surrounded by Application, and finally Infrastructure (DB/API). This ensures your business logic doesn’t depend on whether you use SQL Server or MongoDB.
.NET Core: Instant Real-time Updates with SignalR
Don’t make your users refresh the page. SignalR handles WebSockets, Server-Sent Events, and Long Polling automatically. await Clients.All.SendAsync(“ReceiveMessage”, “New Order Received!”);
.NET Core: Structured Logging with Serilog and Seq
Flat text logs are useless in production. Use Structured Logging to search your logs like a database. Log.Information(“User {UserId} logged in from {Ip}”, user.Id, ip); This allows you to filter logs by ‘UserId’ instantly, making bug tracking a breeze.
















