πΊοΈ Routing = Clean URLs URLs matter. Routing maps URLs to code. Clean, semantic, SEO-friendly. π Routing Basics // Program.cs var app = builder.Build(); // Basic routing app.MapGet(“/”, () => “Hello World!”); app.MapGet(“/users”, () => new[] { new { Id = 1, Name = “Alice” } }); app.MapGet(“/users/{id:int}”, (int id) => new { Id = […]
Category: Asp.Net Core
.NET Core: Manage Configuration with appsettings
βοΈ Configuration = appsettings Hardcoding config is bad. appsettings externalizes configuration. JSON, environment, secrets. π appsettings.json // appsettings.json { “Logging”: { “LogLevel”: { “Default”: “Information”, “Microsoft”: “Warning” } }, “AllowedHosts”: “*”, “ConnectionStrings”: { “DefaultConnection”: “Server=localhost;Database=MyDb;User=sa;Password=MyPass123;” }, “AppSettings”: { “ApiKey”: “abc-123-xyz”, “Timeout”: 30, “RetryCount”: 3, “EnableLogging”: true, “BaseUrl”: “https://api.example.com” } } // appsettings.Development.json (override) { “AppSettings”: […]
.NET Core: Build Background Tasks with Worker Services
βοΈ Worker Services = Background Tasks Apps need background tasks. Worker Services run in background. Scheduling, queues, monitoring. π Worker Setup # Create Worker Project dotnet new worker -n MyWorker cd MyWorker # Program.cs using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; var host = Host.CreateDefaultBuilder(args) .ConfigureServices(services => { services.AddHostedService(); services.AddScoped(); }) .Build(); await host.RunAsync(); # Worker Service public […]
.NET Core: Use Output Caching for Performance
β‘ Output Caching = Performance Repeated requests are wasteful. Output caching saves results. Faster responses, lower server load. π Output Caching Setup // Install package dotnet add package Microsoft.AspNetCore.OutputCaching // Program.cs builder.Services.AddOutputCache(options => { options.AddBasePolicy(builder => { builder.Expire(TimeSpan.FromMinutes(10)); }); options.AddPolicy(“ShortCache”, builder => { builder.Expire(TimeSpan.FromSeconds(30)); }); options.AddPolicy(“LongCache”, builder => { builder.Expire(TimeSpan.FromHours(1)); }); options.AddPolicy(“VaryByQuery”, builder => { […]
.NET Core: Add Globalization for Localization
π Globalization = Localization Reach global audience. Globalization adds localization. Multiple languages, cultures, formats. π Setup // Program.cs builder.Services.AddLocalization(options => options.ResourcesPath = “Resources”); builder.Services.AddControllersWithViews() .AddViewLocalization() .AddDataAnnotationsLocalization(); builder.Services.Configure(options => { var supportedCultures = new[] { new CultureInfo(“en-US”), new CultureInfo(“tr-TR”), new CultureInfo(“de-DE”), new CultureInfo(“fr-FR”) }; options.DefaultRequestCulture = new RequestCulture(“en-US”); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; }); app.UseRequestLocalization(); […]
.NET Core: Use HttpClientFactory for Efficient HTTP
π HttpClientFactory = Efficient HTTP HttpClient has problems. HttpClientFactory solves them. Pooling, resilience, named clients. β Manual HttpClient using var client = new HttpClient(); client.BaseAddress = new Uri(“https://api.example.com”); var response = await client.GetAsync(“/data”); β HttpClientFactory builder.Services.AddHttpClient(); var client = httpClientFactory.CreateClient(); client.BaseAddress = new Uri(“https://api.example.com”); π HttpClientFactory Setup // Program.cs builder.Services.AddHttpClient(); // Named client builder.Services.AddHttpClient(“GitHub”, client […]
.NET Core: Configure CORS for API Security
π CORS = API Security Browsers block cross-origin requests. CORS configuration enables secure API access. Essential for modern APIs. π CORS Setup // Program.cs var builder = WebApplication.CreateBuilder(args); // Add CORS policy builder.Services.AddCors(options => { options.AddPolicy(“AllowSpecificOrigin”, builder => { builder.WithOrigins(“https://myapp.com”) .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); }); options.AddPolicy(“AllowAll”, builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); options.AddPolicy(“AllowMultipleOrigins”, builder => […]
.NET Core: Use Health Checks for Monitoring
π₯ Health Checks = Monitoring Apps fail silently. Health checks monitor app health. Database, cache, services β all in one. π Health Check Setup # Install package dotnet add package Microsoft.AspNetCore.Diagnostics.HealthChecks # Program.cs var builder = WebApplication.CreateBuilder(args); // Add health checks builder.Services.AddHealthChecks() .AddDbContextCheck() .AddUrlGroup(new Uri(“https://api.example.com”), “External API”) .AddCheck(“Custom”) .AddCheck(“Memory”, new MemoryHealthCheck(512)); var app = builder.Build(); […]
.NET Core: Use SignalR for Real-Time Web Apps
π‘ SignalR = Real-Time Web Real-time is essential. SignalR adds real-time to .NET. Chat, notifications, live updates β simple and powerful. π SignalR Setup # Install packages dotnet add package Microsoft.AspNetCore.SignalR dotnet add package Microsoft.AspNetCore.SignalR.Client # Program.cs builder.Services.AddSignalR(); app.MapHub(“/chatHub”); # Create Hub public class ChatHub : Hub { public async Task SendMessage(string user, string message) […]
.NET Core: Use Options Pattern for Configuration
βοΈ Options Pattern = Configuration Configuration is essential. Options Pattern binds configuration to objects. Strongly typed, easy to use. π Options Setup // appsettings.json { “AppSettings”: { “ApiKey”: “abc-123-xyz”, “Timeout”: 30, “RetryCount”: 3, “EnableLogging”: true, “BaseUrl”: “https://api.example.com” } } // Options class public class AppSettings { public string ApiKey { get; set; } public int […]
.NET Core: Build Lightweight APIs with Minimal APIs
β‘ Minimal APIs = Lightweight Endpoints Controllers are heavy. Minimal APIs are lightweight. Single-file APIs, faster development, microservices. π Minimal API Setup // Program.cs (Minimal API) var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); // Basic endpoints app.MapGet(“/”, () => “Hello World!”); app.MapGet(“/users”, () => new[] { new { Id = 1, Name = “Alice” […]
.NET Core: Master Logging with Serilog and NLog
π Logging = Debugging & Monitoring Debugging is hard without logs. Serilog, NLog provide structured logging. Debug, monitor, analyze β powerful logging. π Serilog Setup # Install packages dotnet add package Serilog dotnet add package Serilog.Extensions.Logging dotnet add package Serilog.Sinks.Console dotnet add package Serilog.Sinks.File dotnet add package Serilog.Sinks.Seq # Program.cs using Serilog; var builder = […]
.NET Core: Use SignalR for Real-Time Web Apps
π‘ SignalR = Real-Time Web Real-time is essential. SignalR adds real-time to .NET. Chat, notifications, live updates β simple and powerful. π Setting Up SignalR # Install packages dotnet add package Microsoft.AspNetCore.SignalR dotnet add package Microsoft.AspNetCore.SignalR.Client # Program.cs builder.Services.AddSignalR(); app.MapHub<ChatHub>(“/chatHub”); # Create Hub public class ChatHub : Hub { public async Task SendMessage(string user, string […]
.NET Core: Use Entity Framework Core for Database Access
ποΈ EF Core = Database ORM SQL is tedious. Entity Framework Core is ORM. Query with C#, change tracking, migrations. Essential for .NET data access. π Setting Up EF Core # Install packages dotnet add package Microsoft.EntityFrameworkCore dotnet add package Microsoft.EntityFrameworkCore.SqlServer dotnet add package Microsoft.EntityFrameworkCore.Design dotnet add package Microsoft.EntityFrameworkCore.Tools # Create DbContext public class AppDbContext […]
.NET Core: Build Web UI with Razor Pages
π Razor Pages = Page-Based Web Apps MVC can be heavy. Razor Pages are page-focused. Simpler, more organized, great for UI. π Razor Page Example // Program.cs builder.Services.AddRazorPages(); app.MapRazorPages(); // Pages/Index.cshtml @page @model IndexModel @{ ViewData[“Title”] = “Home”; } <div class=”text-center”> <h1>Welcome to My App</h1> <p>Current time: @Model.CurrentTime</p> <form method=”post”> <input type=”text” asp-for=”UserName” /> <button […]
.NET Core: Manage Configuration with AppSettings
βοΈ Configuration = App Settings Hardcoding config is bad. AppSettings externalizes configuration. JSON, environment, secrets β all in one. π AppSettings.json // appsettings.json { “Logging”: { “LogLevel”: { “Default”: “Information”, “Microsoft”: “Warning”, “Microsoft.Hosting.Lifetime”: “Information” } }, “AllowedHosts”: “*”, “ConnectionStrings”: { “DefaultConnection”: “Server=localhost;Database=MyDb;User=sa;Password=MyPass123;” }, “AppSettings”: { “ApiKey”: “abc-123-xyz”, “Timeout”: 30, “RetryCount”: 3, “EnableLogging”: true, “BaseUrl”: “https://api.example.com” […]
.NET Core: Use Middleware to Handle HTTP Requests
π Middleware = Request Pipeline Each request goes through pipeline. Middleware processes requests and responses. Logging, auth, error handling β all in pipeline. π Basic Middleware // Program.cs var app = builder.Build(); // Built-in middleware app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); // Custom middleware (lambda) app.Use(async (context, next) => { Console.WriteLine($”Request: {context.Request.Method} {context.Request.Path}”); await next(); Console.WriteLine($”Response: […]
.NET Core: Use Dependency Injection for Loose Coupling
π DI = Loose Coupling Tight coupling makes code inflexible. Dependency Injection decouples classes. Testable, maintainable, flexible. β Tight Coupling public class UserService { private readonly EmailService _emailService; public UserService() { _emailService = new EmailService(); } } β Dependency Injection public class UserService { private readonly IEmailService _emailService; public UserService(IEmailService emailService) { _emailService = emailService; […]
Strategy Pattern & Pipeline Pattern in C# .NET – A Deep Dive with Real-World Examples
Two of the most practical design patterns you will reach for in enterprise .NET development are the Strategy Pattern and the Pipeline Pattern. They solve different problems β but they complement each other beautifully, and understanding both will change the way you architect complex business logic. In this post we go from first principles to […]
.NET Core: Use HttpClient to Call External APIs
π HttpClient = Call External APIs Need to call external APIs? HttpClient makes HTTP requests. GET, POST, PUT, DELETE β integrate with any API. π Using HttpClient // Program.cs builder.Services.AddHttpClient(); // Service public class ApiService { private readonly HttpClient _httpClient; public ApiService(HttpClient httpClient) { _httpClient = httpClient; _httpClient.BaseAddress = new Uri(“https://api.example.com”); _httpClient.DefaultRequestHeaders.Add(“User-Agent”, “MyApp”); } public […]
.NET Core: Use Entity Framework Migrations for Database Changes
π¦ Manage Database Schema Changes Database schema changes are hard. EF Migrations track changes. Add columns, tables, relationships β version controlled. π Create Migration # Install tools dotnet tool install –global dotnet-ef # Create migration dotnet ef migrations add AddUserTable # Apply migration dotnet ef database update # Create migration with name dotnet ef migrations […]
.NET Core: Serve Static Files (CSS, JS, Images)
π Serve CSS, JS, Images with Ease Web apps need static files. UseStaticFiles middleware serves CSS, JS, images. Essential for any web app. π Serving Static Files // Program.cs var app = builder.Build(); // Serve files from wwwroot app.UseStaticFiles(); // Custom directory app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), “MyFiles”)), RequestPath = “/myfiles” }); […]
.NET Core: Use API Controllers for RESTful Services
π Build REST APIs with Controllers REST APIs need structure. API Controllers handle HTTP requests. GET, POST, PUT, DELETE β clean and organized. π Basic API Controller [ApiController] [Route(“api/[controller]”)] public class UsersController : ControllerBase { private readonly IUserService _userService; public UsersController(IUserService userService) { _userService = userService; } [HttpGet] public async Task GetUsers() { var users […]
.NET Core: Use Identity for User Authentication
π Identity = Built-in Authentication User login, registration, password reset. ASP.NET Core Identity handles it all. Secure, extensible, built-in. π Setup Identity # Install packages dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore dotnet add package Microsoft.EntityFrameworkCore.SqlServer # Program.cs builder.Services.AddDbContext(options => options.UseSqlServer(connectionString)); builder.Services.AddIdentity() .AddEntityFrameworkStores() .AddDefaultTokenProviders(); builder.Services.Configure(options => { // Password settings options.Password.RequireDigit = true; options.Password.RequiredLength = 8; options.Password.RequireNonAlphanumeric = […]
.NET Core: Use Minimal APIs for Lightweight Services
β‘ APIs in 10 Lines of Code Controllers are overkill for simple APIs. Minimal APIs are lightweight, fast, and simple. Perfect for microservices. β Controller (Verbose) [ApiController] [Route(“api/[controller]”)] public class UsersController : ControllerBase { [HttpGet] public async Task Get() { return await _db.Users.ToListAsync(); } } β Minimal API var app = builder.Build(); app.MapGet(“/api/users”, async (AppDbContext […]
.NET Core: Use Authorization for Access Control
π Authorization = Who Can Access Authentication identifies users. Authorization controls access. Roles, policies, permissions β fine-grained control. π Role-Based Authorization [Authorize(Roles = “Admin”)] public class AdminController : Controller { public IActionResult Dashboard() { } } [Authorize(Roles = “Admin,Manager”)] public IActionResult Reports() { } // In Program.cs builder.Services.AddAuthorization(options => { options.AddPolicy(“AdminOnly”, policy => policy.RequireRole(“Admin”)); }); […]
.NET Core: Understand Routing for URL Mapping
πΊοΈ Routing Maps URLs to Controllers URLs need to go somewhere. Routing maps /api/users to UsersController. Clean, organized, discoverable. π Attribute Routing [ApiController] [Route(“api/[controller]”)] public class UsersController : ControllerBase { [HttpGet] public IActionResult GetUsers() { } [HttpGet(“{id}”)] public IActionResult GetUser(int id) { } [HttpPost] public IActionResult CreateUser(User user) { } [HttpPut(“{id}”)] public IActionResult UpdateUser(int id, […]
.NET Core: Use Data Annotations for Model Validation
β Validate Models with Attributes Manual validation is repetitive. Data Annotations validate models automatically. Clean code, automatic error messages. π Model with Annotations public class User { [Required(ErrorMessage = “Name is required”)] [StringLength(100, MinimumLength = 2)] public string Name { get; set; } [Required(ErrorMessage = “Email is required”)] [EmailAddress(ErrorMessage = “Invalid email format”)] public string […]
.NET Core: Use appsettings.json for Configuration
π appsettings.json = Central Configuration Hardcoded config is bad. appsettings.json stores settings. Change without recompiling. Environment-specific files. π appsettings.json { “Logging”: { “LogLevel”: { “Default”: “Information”, “Microsoft”: “Warning” } }, “Database”: { “ConnectionString”: “Server=localhost;Database=MyDb”, “Timeout”: 30, “MaxConnections”: 100 }, “Email”: { “SmtpServer”: “smtp.gmail.com”, “SmtpPort”: 587, “Username”: “user@gmail.com”, “Password”: “secret” }, “FeatureFlags”: { “NewDashboard”: true, “DarkMode”: […]
.NET Core: Use Middleware to Handle Requests
π Middleware = Pipeline for HTTP Requests Every request goes through pipeline. Middleware intercepts, modifies, logs, authenticates. Order matters. π Basic Middleware public class RequestLoggingMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; public RequestLoggingMiddleware(RequestDelegate next, ILogger logger) { _next = next; _logger = logger; } public async Task InvokeAsync(HttpContext context) { _logger.LogInformation($”Request: {context.Request.Method} […]

