Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Category: Asp.Net Core

Asp.Net Core

.NET Core: Use Background Services for Long-Running Tasks

- 30.03.26 - ErcanOPAK comment on .NET Core: Use Background Services for Long-Running Tasks

โฐ 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; […]

Read More
Asp.Net Core

.NET Core: Use Minimal APIs for Lightweight HTTP Services

- 30.03.26 - ErcanOPAK comment on .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 […]

Read More
Asp.Net Core

.NET Core: Add Health Checks to Monitor Application Status

- 22.03.26 - ErcanOPAK comment on .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: […]

Read More
Asp.Net Core

.NET Core: Use IHostedService for Background Tasks

- 22.03.26 - ErcanOPAK comment on .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 […]

Read More
Asp.Net Core

.NET Core: Use Result Pattern Instead of Throwing Exceptions

- 19.03.26 - ErcanOPAK comment on .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 […]

Read More
Asp.Net Core

.NET Core: Use Minimal APIs for Lightweight Endpoints

- 19.03.26 - ErcanOPAK comment on .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 […]

Read More
Asp.Net Core

.NET Core: Use Health Checks for Monitoring

- 19.03.26 | 19.03.26 - ErcanOPAK comment on .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”); } […]

Read More
Asp.Net Core

.NET Core: Use Response Caching Middleware for Static APIs

- 19.03.26 | 19.03.26 - ErcanOPAK comment on .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 […]

Read More
Asp.Net Core

.NET Core: Use IHostedService for Startup/Shutdown Logic

- 19.03.26 | 19.03.26 - ErcanOPAK comment on .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(); } } // […]

Read More
Asp.Net Core

.NET Core: Use IMemoryCache for In-Memory Caching Without Redis

- 19.03.26 | 19.03.26 - ErcanOPAK comment on .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 […]

Read More
Asp.Net Core

.NET Core: Handling Errors Gracefully with Middleware

- 01.03.26 - ErcanOPAK comment on .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’.

Read More
Asp.Net Core

.NET Core: Mastering Service Lifetimes (A Visual Guide)

- 01.03.26 - ErcanOPAK comment on .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.

Read More
Asp.Net Core

.NET Core: Architecting Scalable Services with Minimal APIs

- 01.03.26 - ErcanOPAK comment on .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.

Read More
Asp.Net Core

.NET Core: High-Performance Code with C# Source Generators

- 01.03.26 - ErcanOPAK comment on .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.

Read More
Asp.Net Core

.NET Core: Native Rate Limiting – Shielding Your API from Abuse

- 01.03.26 - ErcanOPAK comment on .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) });

Read More
Asp.Net Core

.NET Core: Streaming Large Data with IAsyncEnumerable

- 01.03.26 - ErcanOPAK comment on .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 […]

Read More
Asp.Net Core

.NET Core: Scaling with Redis and IDistributedCache

- 28.02.26 - ErcanOPAK comment on .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.

Read More
Asp.Net Core

.NET Core: Zero-Startup Latency with Native AOT Compilation

- 28.02.26 - ErcanOPAK comment on .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.

Read More
Asp.Net Core

.NET Core: Reducing Data Transfer Costs with Response Compression

- 28.02.26 - ErcanOPAK comment on .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.

Read More
Asp.Net Core

.NET Core: Implementing Professional Monitoring with Health Checks

- 28.02.26 - ErcanOPAK comment on .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.

Read More
Asp.Net Core

.NET Core: Implementing a Global Exception Handler for Clean Controllers

- 28.02.26 - ErcanOPAK comment on .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” }); }); });

Read More
Asp.Net Core

.NET Core: Preventing ‘Captive Dependency’ Memory Leaks

- 28.02.26 - ErcanOPAK comment on .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.

Read More
Asp.Net Core

.NET Core Background Services: Running Tasks Without Blocking Your API

- 23.02.26 | 23.02.26 - ErcanOPAK comment on .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 […]

Read More
Asp.Net Core

.NET Core Middleware: Building a Production-Grade Request Pipeline

- 23.02.26 | 23.02.26 - ErcanOPAK comment on .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) โ”‚ โ”‚ […]

Read More
Asp.Net Core

.NET Core: Use HttpClientFactory to Prevent Socket Exhaustion

- 22.02.26 | 22.02.26 - ErcanOPAK comment on .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 […]

Read More
Asp.Net Core

.NET Core: Use ActionFilters for Cross-Cutting Concerns

- 22.02.26 | 22.02.26 - ErcanOPAK comment on .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 […]

Read More
Asp.Net Core

.NET Core: High Performance Microservices with Minimal APIs

- 21.02.26 - ErcanOPAK comment on .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));

Read More
Asp.Net Core

.NET Core: Implementing Clean Architecture for Enterprise Apps

- 21.02.26 - ErcanOPAK comment on .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.

Read More
Asp.Net Core

.NET Core: Instant Real-time Updates with SignalR

- 21.02.26 - ErcanOPAK comment on .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!”);

Read More
Asp.Net Core

.NET Core: Structured Logging with Serilog and Seq

- 21.02.26 - ErcanOPAK comment on .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.

Read More
Page 1 of 7
1 2 3 4 5 6 7 Next ยป

Posts navigation

Older posts
April 2026
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
27282930  
« Mar    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (950)
  • How to add default value for Entity Framework migrations for DateTime and Bool (859)
  • Get the First and Last Word from a String or Sentence in SQL (836)
  • How to select distinct rows in a datatable in C# (805)
  • How to make theater mode the default for Youtube (754)
  • Add Constraint to SQL Table to ensure email contains @ (578)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (564)
  • Average of all values in a column that are not zero in SQL (531)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (489)
  • Find numbers with more than two decimal places in SQL (448)

Recent Posts

  • C#: Use Init-Only Setters for Immutable Objects After Construction
  • C#: Use Expression-Bodied Members for Concise Single-Line Methods
  • C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
  • C#: Use Record Types for Immutable Data Objects
  • SQL: Use CTEs for Readable Complex Queries
  • SQL: Use Window Functions for Advanced Analytical Queries
  • .NET Core: Use Background Services for Long-Running Tasks
  • .NET Core: Use Minimal APIs for Lightweight HTTP Services
  • Git: Use Cherry-Pick to Apply Specific Commits Across Branches
  • Git: Use Interactive Rebase to Clean Up Commit History Before Merge

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (950)
  • How to add default value for Entity Framework migrations for DateTime and Bool (859)
  • Get the First and Last Word from a String or Sentence in SQL (836)
  • How to select distinct rows in a datatable in C# (805)
  • How to make theater mode the default for Youtube (754)

Recent Posts

  • C#: Use Init-Only Setters for Immutable Objects After Construction
  • C#: Use Expression-Bodied Members for Concise Single-Line Methods
  • C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
  • C#: Use Record Types for Immutable Data Objects
  • SQL: Use CTEs for Readable Complex Queries

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com