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: Master Routing for Clean URLs

- 12.07.26 - ErcanOPAK comment on .NET Core: Master Routing for Clean URLs

πŸ—ΊοΈ 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 = […]

Read More
Asp.Net Core

.NET Core: Manage Configuration with appsettings

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

Read More
Asp.Net Core

.NET Core: Build Background Tasks with Worker Services

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

Read More
Asp.Net Core

.NET Core: Use Output Caching for Performance

- 11.07.26 - ErcanOPAK comment on .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 => { […]

Read More
Asp.Net Core

.NET Core: Add Globalization for Localization

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

Read More
Asp.Net Core

.NET Core: Use HttpClientFactory for Efficient HTTP

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

Read More
Asp.Net Core

.NET Core: Configure CORS for API Security

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

Read More
Asp.Net Core

.NET Core: Use Health Checks for Monitoring

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

Read More
Asp.Net Core

.NET Core: Use SignalR for Real-Time Web Apps

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

Read More
Asp.Net Core

.NET Core: Use Options Pattern for Configuration

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

Read More
Asp.Net Core

.NET Core: Build Lightweight APIs with Minimal APIs

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

Read More
Asp.Net Core

.NET Core: Master Logging with Serilog and NLog

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

Read More
Asp.Net Core

.NET Core: Use SignalR for Real-Time Web Apps

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

Read More
Asp.Net Core

.NET Core: Use Entity Framework Core for Database Access

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

Read More
Asp.Net Core

.NET Core: Build Web UI with Razor Pages

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

Read More
Asp.Net Core

.NET Core: Manage Configuration with AppSettings

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

Read More
Asp.Net Core

.NET Core: Use Middleware to Handle HTTP Requests

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

Read More
Asp.Net Core

.NET Core: Use Dependency Injection for Loose Coupling

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

Read More
Asp.Net Core / ASP.Net MVC / ASP.Net WebForms / C# / YazΔ±lΔ±m

Strategy Pattern & Pipeline Pattern in C# .NET – A Deep Dive with Real-World Examples

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

Read More
Asp.Net Core

.NET Core: Use HttpClient to Call External APIs

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

Read More
Asp.Net Core

.NET Core: Use Entity Framework Migrations for Database Changes

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

Read More
Asp.Net Core

.NET Core: Serve Static Files (CSS, JS, Images)

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

Read More
Asp.Net Core

.NET Core: Use API Controllers for RESTful Services

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

Read More
Asp.Net Core

.NET Core: Use Identity for User Authentication

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

Read More
Asp.Net Core

.NET Core: Use Minimal APIs for Lightweight Services

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

Read More
Asp.Net Core

.NET Core: Use Authorization for Access Control

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

Read More
Asp.Net Core

.NET Core: Understand Routing for URL Mapping

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

Read More
Asp.Net Core

.NET Core: Use Data Annotations for Model Validation

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

Read More
Asp.Net Core

.NET Core: Use appsettings.json for Configuration

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

Read More
Asp.Net Core

.NET Core: Use Middleware to Handle Requests

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

Read More
Page 1 of 8
1 2 3 4 5 6 … 8 Next Β»

Posts pagination

1 2 3 … 8 Next »
July 2026
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  
« Jun    

Most Viewed Posts

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

Recent Posts

  • C#: Use Using Statements for Resource Management
  • C#: Use Lambda Expressions for Concise Code
  • SQL: Use GROUP BY for Data Aggregation
  • .NET Core: Master Routing for Clean URLs
  • Git: Use Reset to Undo Local Changes
  • Ajax: Use Axios for HTTP Requests
  • JavaScript: Understand Hoisting
  • HTML: Use Web Storage for Client-Side Data
  • CSS: Use Filter Effects for Visual Magic
  • Windows 11: Unlock God Mode for All Settings

Most Viewed Posts

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

Recent Posts

  • C#: Use Using Statements for Resource Management
  • C#: Use Lambda Expressions for Concise Code
  • SQL: Use GROUP BY for Data Aggregation
  • .NET Core: Master Routing for Clean URLs
  • Git: Use Reset to Undo Local Changes

Social

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