.NET & C# Development Skill
Expert guidance for building modern .NET 8+ applications with C#, ASP.NET Core, Entity Framework Core, and best practices.
📑 Table of Contents
📋 Quick Reference
.NET CLI Commands
| Command |
Description |
dotnet new webapi |
Create new Web API project |
dotnet new mvc |
Create new MVC project |
dotnet new classlib |
Create class library |
dotnet new xunit |
Create xUnit test project |
dotnet build |
Build the project |
dotnet run |
Run the application |
dotnet test |
Run tests |
dotnet publish -c Release |
Publish for deployment |
dotnet ef migrations add <Name> |
Create EF migration |
dotnet ef database update |
Apply migrations |
Project Templates
| Template |
Use Case |
webapi |
REST API with controllers or minimal APIs |
web |
Empty ASP.NET Core project |
mvc |
MVC web application |
razor |
Razor Pages application |
blazorserver |
Blazor Server app |
blazorwasm |
Blazor WebAssembly app |
worker |
Background service |
grpc |
gRPC service |
C# 12 Features (.NET 8+)
| Feature |
Example |
| Primary Constructors |
class Person(string name, int age) |
| Collection Expressions |
int[] nums = [1, 2, 3]; |
| Alias Any Type |
using Point = (int X, int Y); |
| Default Lambda Parameters |
var add = (int a, int b = 1) => a + b; |
| Inline Arrays |
[InlineArray(10)] struct Buffer { int _element; } |
🚀 Project Setup
Solution Structure
MySolution/
├── src/
│ ├── MyApp.Api/ # Web API project
│ │ ├── Controllers/
│ │ ├── Endpoints/ # Minimal API endpoints
│ │ ├── Middleware/
│ │ ├── Program.cs
│ │ └── appsettings.json
│ ├── MyApp.Core/ # Domain/business logic
│ │ ├── Entities/
│ │ ├── Interfaces/
│ │ └── Services/
│ ├── MyApp.Infrastructure/ # Data access, external services
│ │ ├── Data/
│ │ ├── Repositories/
│ │ └── Services/
│ └── MyApp.Shared/ # Shared DTOs, utilities
│ ├── DTOs/
│ └── Extensions/
├── tests/
│ ├── MyApp.UnitTests/
│ ├── MyApp.IntegrationTests/
│ └── MyApp.FunctionalTests/
├── Directory.Build.props # Shared build properties
├── Directory.Packages.props # Central package management
└── MySolution.sln
Directory.Build.props
<Project>
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AnalysisLevel>latest-recommended</AnalysisLevel>
</PropertyGroup>
</Project>
Central Package Management (Directory.Packages.props)
<Project>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Microsoft.EntityFrameworkCore" Version="8.0.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.0" />
<PackageVersion Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageVersion Include="FluentValidation" Version="11.9.0" />
<PackageVersion Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageVersion Include="xunit" Version="2.6.4" />
<PackageVersion Include="Moq" Version="4.20.70" />
</ItemGroup>
</Project>
🌐 ASP.NET Core
Program.cs (Modern Setup)
using MyApp.Api.Middleware;
using MyApp.Core.Interfaces;
using MyApp.Infrastructure.Data;
using MyApp.Infrastructure.Services;
var builder = WebApplication.CreateBuilder(args);
// Configuration
builder.Configuration
.AddJsonFile("appsettings.json", optional: false)
.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables()
.AddUserSecrets<Program>(optional: true);
// Services
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Database
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Application services
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IEmailService, EmailService>();
// Health checks
builder.Services.AddHealthChecks()
.AddDbContextCheck<AppDbContext>();
var app = builder.Build();
// Middleware pipeline
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<ExceptionHandlingMiddleware>();
app.MapControllers();
app.MapHealthChecks("/health");
app.Run();
// Make Program class accessible for integration tests
public partial class Program { }
Controller Pattern
using Microsoft.AspNetCore.Mvc;
namespace MyApp.Api.Controllers;
[ApiController]
[Route("api/[controller]")]
[Produces("application/json")]
public class UsersController : ControllerBase
{
private readonly IUserService _userService;
private readonly ILogger<UsersController> _logger;
public UsersController(IUserService userService, ILogger<UsersController> logger)
{
_userService = userService;
_logger = logger;
}
/// <summary>
/// Gets all users with optional filtering
/// </summary>
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<UserDto>), StatusCodes.Status200OK)]
public async Task<ActionResult<IEnumerable<UserDto>>> GetUsers(
[FromQuery] string? search = null,
[FromQuery] int page = 1,
[FromQuery] int pageSize = 10,
CancellationToken cancellationToken = default)
{
var users = await _userService.GetUsersAsync(search, page, pageSize, cancellationToken);
return Ok(users);
}
/// <summary>
/// Gets a specific user by ID
/// </summary>
[HttpGet("{id:guid}")]
[ProducesResponseType(typeof(UserDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<UserDto>> GetUser(
Guid id,
CancellationToken cancellationToken = default)
{
var user = await _userService.GetByIdAsync(id, cancellationToken);
if (user is null)
{
return NotFound();
}
return Ok(user);
}
/// <summary>
/// Creates a new user
/// </summary>
[HttpPost]
[ProducesResponseType(typeof(UserDto), StatusCodes.Status201Created)]
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)]
public async Task<ActionResult<UserDto>> CreateUser(
[FromBody] CreateUserRequest request,
CancellationToken cancellationToken = default)
{
var user = await _userService.CreateAsync(request, cancellationToken);
_logger.LogInformation("Created user {UserId}", user.Id);
return CreatedAtAction(
nameof(GetUser),
new { id = user.Id },
user);
}
/// <summary>
/// Updates an existing user
/// </summary>
[HttpPut("{id:guid}")]
[ProducesResponseType(typeof(UserDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<UserDto>> UpdateUser(
Guid id,
[FromBody] UpdateUserRequest request,
CancellationToken cancellationToken = default)
{
var user = await _userService.UpdateAsync(id, request, cancellationToken);
if (user is null)
{
return NotFound();
}
return Ok(user);
}
/// <summary>
/// Deletes a user
/// </summary>
[HttpDelete("{id:guid}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> DeleteUser(
Guid id,
CancellationToken cancellationToken = default)
{
var deleted = await _userService.DeleteAsync(id, cancellationToken);
if (!deleted)
{
return NotFound();
}
return NoContent();
}
}
⚡ Minimal APIs
Basic Setup
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddScoped<IUserService, UserService>();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
// Map endpoints
app.MapUserEndpoints();
app.MapProductEndpoints();
app.Run();
Organized Endpoints
namespace MyApp.Api.Endpoints;
public static class UserEndpoints
{
public static void MapUserEndpoints(this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup("/api/users")
.WithTags("Users")
.WithOpenApi();
group.MapGet("/", GetUsers)
.WithName("GetUsers")
.WithSummary("Gets all users");
group.MapGet("/{id:guid}", GetUserById)
.WithName("GetUserById")
.WithSummary("Gets a user by ID");
group.MapPost("/", CreateUser)
.WithName("CreateUser")
.WithSummary("Creates a new user")
.AddEndpointFilter<ValidationFilter<CreateUserRequest>>();
group.MapPut("/{id:guid}", UpdateUser)
.WithName("UpdateUser")
.RequireAuthorization();
group.MapDelete("/{id:guid}", DeleteUser)
.WithName("DeleteUser")
.RequireAuthorization("AdminOnly");
}
private static async Task<IResult> GetUsers(
IUserService userService,
[AsParameters] PaginationQuery pagination,
CancellationToken cancellationToken)
{
var users = await userService.GetUsersAsync(
pagination.Page,
pagination.PageSize,
cancellationToken);
return Results.Ok(users);
}
private static async Task<IResult> GetUserById(
Guid id,
IUserService userService,
CancellationToken cancellationToken)
{
var user = await userService.GetByIdAsync(id, cancellationToken);
return user is null
? Results.NotFound()
: Results.Ok(user);
}
private static async Task<IResult> CreateUser(
CreateUserRequest request,
IUserService userService,
CancellationToken cancellationToken)
{
var user = await userService.CreateAsync(request, cancellationToken);
return Results.CreatedAtRoute(
"GetUserById",
new { id = user.Id },
user);
}
private static async Task<IResult> UpdateUser(
Guid id,
UpdateUserRequest request,
IUserService userService,
CancellationToken cancellationToken)
{
var user = await userService.UpdateAsync(id, request, cancellationToken);
return user is null
? Results.NotFound()
: Results.Ok(user);
}
private static async Task<IResult> DeleteUser(
Guid id,
IUserService userService,
CancellationToken cancellationToken)
{
var deleted = await userService.DeleteAsync(id, cancellationToken);
return deleted
? Results.NoContent()
: Results.NotFound();
}
}
// Parameter binding class
public record PaginationQuery(
[FromQuery] int Page = 1,
[FromQuery] int PageSize = 10);
Typed Results (Better OpenAPI)
public static class UserEndpoints
{
public static void MapUserEndpoints(this IEndpointRouteBuilder routes)
{
routes.MapGet("/api/users/{id:guid}", GetUserById);
}
private static async Task<Results<Ok<UserDto>, NotFound>> GetUserById(
Guid id,
IUserService userService,
CancellationToken cancellationToken)
{
var user = await userService.GetByIdAsync(id, cancellationToken);
return user is null
? TypedResults.NotFound()
: TypedResults.Ok(user);
}
}
🗄️ Entity Framework Core
DbContext
using Microsoft.EntityFrameworkCore;
namespace MyApp.Infrastructure.Data;
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<User> Users => Set<User>();
public DbSet<Order> Orders => Set<Order>();
public DbSet<Product> Products => Set<Product>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Apply all configurations from assembly
modelBuilder.ApplyConfigurationsFromAssembly(
typeof(AppDbContext).Assembly);
// Global query filters
modelBuilder.Entity<User>()
.HasQueryFilter(u => !u.IsDeleted);
base.OnModelCreating(modelBuilder);
}
public override async Task<int> SaveChangesAsync(
CancellationToken cancellationToken = default)
{
// Audit trail
foreach (var entry in ChangeTracker.Entries<IAuditable>())
{
switch (entry.State)
{
case EntityState.Added:
entry.Entity.CreatedAt = DateTime.UtcNow;
break;
case EntityState.Modified:
entry.Entity.UpdatedAt = DateTime.UtcNow;
break;
}
}
return await base.SaveChangesAsync(cancellationToken);
}
}
Entity Configuration
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace MyApp.Infrastructure.Data.Configurations;
public class UserConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder.ToTable("Users");
builder.HasKey(u => u.Id);
builder.Property(u => u.Id)
.ValueGeneratedOnAdd();
builder.Property(u => u.Email)
.IsRequired()
.HasMaxLength(256);
builder.Property(u => u.FirstName)
.IsRequired()
.HasMaxLength(100);
builder.Property(u => u.LastName)
.IsRequired()
.HasMaxLength(100);
builder.Property(u => u.PasswordHash)
.IsRequired();
// Indexes
builder.HasIndex(u => u.Email)
.IsUnique();
// Relationships
builder.HasMany(u => u.Orders)
.WithOne(o => o.User)
.HasForeignKey(o => o.UserId)
.OnDelete(DeleteBehavior.Cascade);
// Value objects
builder.OwnsOne(u => u.Address, address =>
{
address.Property(a => a.Street).HasMaxLength(200);
address.Property(a => a.City).HasMaxLength(100);
address.Property(a => a.ZipCode).HasMaxLength(20);
address.Property(a => a.Country).HasMaxLength(100);
});
// Seed data
builder.HasData(
new User
{
Id = Guid.Parse("11111111-1111-1111-1111-111111111111"),
Email = "admin@example.com",
FirstName = "Admin",
LastName = "User"
});
}
}
Repository Pattern
namespace MyApp.Core.Interfaces;
public interface IRepository<T> where T : class
{
Task<T?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default);
Task<IReadOnlyList<T>> GetAllAsync(CancellationToken cancellationToken = default);
Task<T> AddAsync(T entity, CancellationToken cancellationToken = default);
Task UpdateAsync(T entity, CancellationToken cancellationToken = default);
Task DeleteAsync(T entity, CancellationToken cancellationToken = default);
}
public interface IUserRepository : IRepository<User>
{
Task<User?> GetByEmailAsync(string email, CancellationToken cancellationToken = default);
Task<IReadOnlyList<User>> GetActiveUsersAsync(CancellationToken cancellationToken = default);
}
namespace MyApp.Infrastructure.Repositories;
public class Repository<T> : IRepository<T> where T : class
{
protected readonly AppDbContext _context;
protected readonly DbSet<T> _dbSet;
public Repository(AppDbContext context)
{
_context = context;
_dbSet = context.Set<T>();
}
public virtual async Task<T?> GetByIdAsync(
Guid id,
CancellationToken cancellationToken = default)
{
return await _dbSet.FindAsync([id], cancellationToken);
}
public virtual async Task<IReadOnlyList<T>> GetAllAsync(
CancellationToken cancellationToken = default)
{
return await _dbSet.ToListAsync(cancellationToken);
}
public virtual async Task<T> AddAsync(
T entity,
CancellationToken cancellationToken = default)
{
await _dbSet.AddAsync(entity, cancellationToken);
await _context.SaveChangesAsync(cancellationToken);
return entity;
}
public virtual async Task UpdateAsync(
T entity,
CancellationToken cancellationToken = default)
{
_dbSet.Update(entity);
await _context.SaveChangesAsync(cancellationToken);
}
public virtual async Task DeleteAsync(
T entity,
CancellationToken cancellationToken = default)
{
_dbSet.Remove(entity);
await _context.SaveChangesAsync(cancellationToken);
}
}
public class UserRepository : Repository<User>, IUserRepository
{
public UserRepository(AppDbContext context) : base(context)
{
}
public async Task<User?> GetByEmailAsync(
string email,
CancellationToken cancellationToken = default)
{
return await _dbSet
.FirstOrDefaultAsync(u => u.Email == email, cancellationToken);
}
public async Task<IReadOnlyList<User>> GetActiveUsersAsync(
CancellationToken cancellationToken = default)
{
return await _dbSet
.Where(u => u.IsActive)
.OrderBy(u => u.LastName)
.ThenBy(u => u.FirstName)
.ToListAsync(cancellationToken);
}
}
Specification Pattern
namespace MyApp.Core.Specifications;
public abstract class Specification<T>
{
public abstract Expression<Func<T, bool>> ToExpression();
public bool IsSatisfiedBy(T entity)
{
var predicate = ToExpression().Compile();
return predicate(entity);
}
public Specification<T> And(Specification<T> specification)
{
return new AndSpecification<T>(this, specification);
}
public Specification<T> Or(Specification<T> specification)
{
return new OrSpecification<T>(this, specification);
}
}
public class ActiveUserSpecification : Specification<User>
{
public override Expression<Func<User, bool>> ToExpression()
{
return user => user.IsActive && !user.IsDeleted;
}
}
public class UserByEmailSpecification : Specification<User>
{
private readonly string _email;
public UserByEmailSpecification(string email)
{
_email = email;
}
public override Expression<Func<User, bool>> ToExpression()
{
return user => user.Email == _email;
}
}
💉 Dependency Injection
Service Registration
namespace MyApp.Api.Extensions;
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddApplicationServices(
this IServiceCollection services)
{
// Transient - new instance every time
services.AddTransient<IEmailService, EmailService>();
// Scoped - one instance per request
services.AddScoped<IUserService, UserService>();
services.AddScoped<IOrderService, OrderService>();
services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
// Singleton - one instance for app lifetime
services.AddSingleton<ICacheService, MemoryCacheService>();
return services;
}
public static IServiceCollection AddInfrastructure(
this IServiceCollection services,
IConfiguration configuration)
{
// Database
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
configuration.GetConnectionString("DefaultConnection"),
sqlOptions =>
{
sqlOptions.EnableRetryOnFailure(
maxRetryCount: 3,
maxRetryDelay: TimeSpan.FromSeconds(30),
errorNumbersToAdd: null);
sqlOptions.CommandTimeout(30);
}));
// Repositories
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<IOrderRepository, OrderRepository>();
// HTTP clients
services.AddHttpClient<IExternalApiClient, ExternalApiClient>(client =>
{
client.BaseAddress = new Uri(configuration["ExternalApi:BaseUrl"]!);
client.Timeout = TimeSpan.FromSeconds(30);
})
.AddPolicyHandler(GetRetryPolicy())
.AddPolicyHandler(GetCircuitBreakerPolicy());
return services;
}
private static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
{
return HttpPolicyExtensions
.HandleTransientHttpError()
.WaitAndRetryAsync(3, retryAttempt =>
TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
}
private static IAsyncPolicy<HttpResponseMessage> GetCircuitBreakerPolicy()
{
return HttpPolicyExtensions
.HandleTransientHttpError()
.CircuitBreakerAsync(5, TimeSpan.FromSeconds(30));
}
}
Keyed Services (.NET 8+)
// Registration
services.AddKeyedScoped<INotificationService, EmailNotificationService>("email");
services.AddKeyedScoped<INotificationService, SmsNotificationService>("sms");
services.AddKeyedScoped<INotificationService, PushNotificationService>("push");
// Injection
public class NotificationController : ControllerBase
{
public NotificationController(
[FromKeyedServices("email")] INotificationService emailService,
[FromKeyedServices("sms")] INotificationService smsService)
{
// Use specific implementations
}
}
Factory Pattern
public interface IPaymentProcessorFactory
{
IPaymentProcessor Create(PaymentMethod method);
}
public class PaymentProcessorFactory : IPaymentProcessorFactory
{
private readonly IServiceProvider _serviceProvider;
public PaymentProcessorFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public IPaymentProcessor Create(PaymentMethod method)
{
return method switch
{
PaymentMethod.CreditCard => _serviceProvider
.GetRequiredService<CreditCardProcessor>(),
PaymentMethod.PayPal => _serviceProvider
.GetRequiredService<PayPalProcessor>(),
PaymentMethod.BankTransfer => _serviceProvider
.GetRequiredService<BankTransferProcessor>(),
_ => throw new ArgumentException($"Unknown payment method: {method}")
};
}
}
// Registration
services.AddScoped<IPaymentProcessorFactory, PaymentProcessorFactory>();
services.AddScoped<CreditCardProcessor>();
services.AddScoped<PayPalProcessor>();
services.AddScoped<BankTransferProcessor>();
⚙️ Configuration & Options
appsettings.json Structure
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=MyApp;Trusted_Connection=true;",
"Redis": "localhost:6379"
},
"Jwt": {
"Secret": "your-secret-key-here",
"Issuer": "MyApp",
"Audience": "MyApp",
"ExpirationMinutes": 60
},
"Email": {
"SmtpServer": "smtp.example.com",
"Port": 587,
"UseSsl": true,
"FromAddress": "noreply@example.com",
"FromName": "MyApp"
},
"Features": {
"EnableNewDashboard": true,
"MaxUploadSizeMb": 10
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore": "Warning"
}
}
}
Options Pattern
namespace MyApp.Core.Options;
public class JwtOptions
{
public const string SectionName = "Jwt";
public string Secret { get; set; } = string.Empty;
public string Issuer { get; set; } = string.Empty;
public string Audience { get; set; } = string.Empty;
public int ExpirationMinutes { get; set; } = 60;
}
public class EmailOptions
{
public const string SectionName = "Email";
public string SmtpServer { get; set; } = string.Empty;
public int Port { get; set; } = 587;
public bool UseSsl { get; set; } = true;
public string FromAddress { get; set; } = string.Empty;
public string FromName { get; set; } = string.Empty;
}
Options Validation
public class JwtOptionsValidator : IValidateOptions<JwtOptions>
{
public ValidateOptionsResult Validate(string? name, JwtOptions options)
{
var failures = new List<string>();
if (string.IsNullOrWhiteSpace(options.Secret))
{
failures.Add("JWT Secret is required");
}
else if (options.Secret.Length < 32)
{
failures.Add("JWT Secret must be at least 32 characters");
}
if (string.IsNullOrWhiteSpace(options.Issuer))
{
failures.Add("JWT Issuer is required");
}
if (options.ExpirationMinutes <= 0)
{
failures.Add("JWT ExpirationMinutes must be positive");
}
return failures.Count > 0
? ValidateOptionsResult.Fail(failures)
: ValidateOptionsResult.Success;
}
}
// Registration
services.AddOptions<JwtOptions>()
.Bind(configuration.GetSection(JwtOptions.SectionName))
.ValidateDataAnnotations()
.ValidateOnStart();
services.AddSingleton<IValidateOptions<JwtOptions>, JwtOptionsValidator>();
Using Options
public class TokenService : ITokenService
{
private readonly JwtOptions _jwtOptions;
// Use IOptions for singleton-scoped options
public TokenService(IOptions<JwtOptions> jwtOptions)
{
_jwtOptions = jwtOptions.Value;
}
// Use IOptionsSnapshot for scoped options (reloads on change)
public TokenService(IOptionsSnapshot<JwtOptions> jwtOptions)
{
_jwtOptions = jwtOptions.Value;
}
// Use IOptionsMonitor for singleton services that need to react to changes
public TokenService(IOptionsMonitor<JwtOptions> jwtOptions)
{
_jwtOptions = jwtOptions.CurrentValue;
jwtOptions.OnChange(newOptions =>
{
// React to configuration changes
});
}
}
🔧 Middleware & Filters
Custom Middleware
namespace MyApp.Api.Middleware;
public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
public ExceptionHandlingMiddleware(
RequestDelegate next,
ILogger<ExceptionHandlingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
_logger.LogError(exception, "An unhandled exception occurred");
var (statusCode, message) = exception switch
{
NotFoundException => (StatusCodes.Status404NotFound, exception.Message),
ValidationException validationEx => (
StatusCodes.Status400BadRequest,
string.Join("; ", validationEx.Errors)),
UnauthorizedAccessException => (
StatusCodes.Status401Unauthorized,
"Unauthorized"),
ForbiddenException => (
StatusCodes.Status403Forbidden,
"Forbidden"),
_ => (
StatusCodes.Status500InternalServerError,
"An error occurred processing your request")
};
context.Response.StatusCode = statusCode;
context.Response.ContentType = "application/problem+json";
var problemDetails = new ProblemDetails
{
Status = statusCode,
Title = GetTitle(statusCode),
Detail = message,
Instance = context.Request.Path
};
await context.Response.WriteAsJsonAsync(problemDetails);
}
private static string GetTitle(int statusCode) => statusCode switch
{
400 => "Bad Request",
401 => "Unauthorized",
403 => "Forbidden",
404 => "Not Found",
_ => "Server Error"
};
}
// Extension method
public static class MiddlewareExtensions
{
public static IApplicationBuilder UseExceptionHandling(
this IApplicationBuilder app)
{
return app.UseMiddleware<ExceptionHandlingMiddleware>();
}
}
Request Logging Middleware
public class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestLoggingMiddleware> _logger;
public RequestLoggingMiddleware(
RequestDelegate next,
ILogger<RequestLoggingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
var stopwatch = Stopwatch.StartNew();
var requestId = Activity.Current?.Id ?? context.TraceIdentifier;
_logger.LogInformation(
"Request started: {Method} {Path} [{RequestId}]",
context.Request.Method,
context.Request.Path,
requestId);
try
{
await _next(context);
}
finally
{
stopwatch.Stop();
_logger.LogInformation(
"Request completed: {Method} {Path} [{RequestId}] - {StatusCode} in {ElapsedMs}ms",
context.Request.Method,
context.Request.Path,
requestId,
context.Response.StatusCode,
stopwatch.ElapsedMilliseconds);
}
}
}
Action Filters
namespace MyApp.Api.Filters;
public class ValidationFilter : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(
ActionExecutingContext context,
ActionExecutionDelegate next)
{
if (!context.ModelState.IsValid)
{
var errors = context.ModelState
.Where(x => x.Value?.Errors.Count > 0)
.ToDictionary(
x => x.Key,
x => x.Value!.Errors.Select(e => e.ErrorMessage).ToArray());
context.Result = new BadRequestObjectResult(
new ValidationProblemDetails(context.ModelState));
return;
}
await next();
}
}
// Minimal API filter
public class ValidationFilter<T> : IEndpointFilter where T : class
{
public async ValueTask<object?> InvokeAsync(
EndpointFilterInvocationContext context,
EndpointFilterDelegate next)
{
var validator = context.HttpContext.RequestServices
.GetService<IValidator<T>>();
if (validator is null)
{
return await next(context);
}
var argument = context.Arguments
.OfType<T>()
.FirstOrDefault();
if (argument is null)
{
return await next(context);
}
var validationResult = await validator.ValidateAsync(argument);
if (!validationResult.IsValid)
{
return Results.ValidationProblem(
validationResult.ToDictionary());
}
return await next(context);
}
}
Exception Filter
public class GlobalExceptionFilter : IExceptionFilter
{
private readonly ILogger<GlobalExceptionFilter> _logger;
private readonly IHostEnvironment _environment;
public GlobalExceptionFilter(
ILogger<GlobalExceptionFilter> logger,
IHostEnvironment environment)
{
_logger = logger;
_environment = environment;
}
public void OnException(ExceptionContext context)
{
_logger.LogError(context.Exception, "Unhandled exception occurred");
var problemDetails = new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError,
Title = "An error occurred",
Detail = _environment.IsDevelopment()
? context.Exception.Message
: "An error occurred processing your request"
};
context.Result = new ObjectResult(problemDetails)
{
StatusCode = StatusCodes.Status500InternalServerError
};
context.ExceptionHandled = true;
}
}
// Registration
services.AddControllers(options =>
{
options.Filters.Add<GlobalExceptionFilter>();
});
🔐 Authentication & Authorization
JWT Authentication
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
public static class AuthenticationExtensions
{
public static IServiceCollection AddJwtAuthentication(
this IServiceCollection services,
IConfiguration configuration)
{
var jwtOptions = configuration
.GetSection(JwtOptions.SectionName)
.Get<JwtOptions>()!;
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtOptions.Issuer,
ValidAudience = jwtOptions.Audience,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(jwtOptions.Secret)),
ClockSkew = TimeSpan.Zero
};
options.Events = new JwtBearerEvents
{
=>
{
if (context.Exception is SecurityTokenExpiredException)
{
context.Response.Headers.Append(
"Token-Expired", "true");
}
return Task.CompletedTask;
}
};
});
return services;
}
}
Token Service
public interface ITokenService
{
string GenerateAccessToken(User user);
string GenerateRefreshToken();
ClaimsPrincipal? ValidateToken(string token);
}
public class TokenService : ITokenService
{
private readonly JwtOptions _options;
public TokenService(IOptions<JwtOptions> options)
{
_options = options.Value;
}
public string GenerateAccessToken(User user)
{
var claims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, user.Id.ToString()),
new(ClaimTypes.Email, user.Email),
new(ClaimTypes.Name, $"{user.FirstName} {user.LastName}"),
new("role", user.Role.ToString())
};
var key = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(_options.Secret));
var credentials = new SigningCredentials(
key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _options.Issuer,
audience: _options.Audience,
claims: claims,
expires: DateTime.UtcNow.AddMinutes(_options.ExpirationMinutes),
signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
public string GenerateRefreshToken()
{
var randomBytes = new byte[64];
using var rng = RandomNumberGenerator.Create();
rng.GetBytes(randomBytes);
return Convert.ToBase64String(randomBytes);
}
public ClaimsPrincipal? ValidateToken(string token)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes(_options.Secret);
try
{
return tokenHandler.ValidateToken(token,
new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = true,
ValidIssuer = _options.Issuer,
ValidateAudience = true,
ValidAudience = _options.Audience,
ValidateLifetime = false // Allow expired tokens for refresh
}, out _);
}
catch
{
return null;
}
}
}
Authorization Policies
public static class AuthorizationExtensions
{
public static IServiceCollection AddAuthorizationPolicies(
this IServiceCollection services)
{
services.AddAuthorization(options =>
{
// Role-based policies
options.AddPolicy("AdminOnly", policy =>
policy.RequireRole("Admin"));
options.AddPolicy("ManagerOrAdmin", policy =>
policy.RequireRole("Manager", "Admin"));
// Claim-based policies
options.AddPolicy("VerifiedEmail", policy =>
policy.RequireClaim("email_verified", "true"));
// Custom requirement policies
options.AddPolicy("MinimumAge", policy =>
policy.AddRequirements(new MinimumAgeRequirement(18)));
// Resource-based authorization
options.AddPolicy("OwnerOnly", policy =>
policy.AddRequirements(new ResourceOwnerRequirement()));
// Combined polic
…(truncated)
1---
2name: dotnet-csharp
3description: "Build .NET 8+ applications with C#. Covers ASP.NET Core, Minimal APIs, Entity Framework Core, dependency injection, and testing. Use for .NET development, C# programming, and Azure backend services."
4metadata:
5 source: https://skillmd.com/skills/aibot88/dotnet-csharp
6---
7
8# .NET & C# Development Skill
9
10> Expert guidance for building modern .NET 8+ applications with C#, ASP.NET Core, Entity Framework Core, and best practices.
11
12---
13
14## 📑 Table of Contents
15
16- [Quick Reference](#-quick-reference)
17- [Project Setup](#-project-setup)
18- [ASP.NET Core](#-aspnet-core)
19- [Minimal APIs](#-minimal-apis)
20- [Entity Framework Core](#-entity-framework-core)
21- [Dependency Injection](#-dependency-injection)
22- [Configuration & Options](#-configuration--options)
23- [Middleware & Filters](#-middleware--filters)
24- [Authentication & Authorization](#-authentication--authorization)
25- [Background Services](#-background-services)
26- [Testing](#-testing)
27- [Common Patterns](#-common-patterns)
28- [Best Practices](#-best-practices)
29
30---
31
32## 📋 Quick Reference
33
34### .NET CLI Commands
35
36| Command | Description |
37| --------------------------------- | -------------------------- |
38| `dotnet new webapi` | Create new Web API project |
39| `dotnet new mvc` | Create new MVC project |
40| `dotnet new classlib` | Create class library |
41| `dotnet new xunit` | Create xUnit test project |
42| `dotnet build` | Build the project |
43| `dotnet run` | Run the application |
44| `dotnet test` | Run tests |
45| `dotnet publish -c Release` | Publish for deployment |
46| `dotnet ef migrations add <Name>` | Create EF migration |
47| `dotnet ef database update` | Apply migrations |
48
49### Project Templates
50
51| Template | Use Case |
52| -------------- | ----------------------------------------- |
53| `webapi` | REST API with controllers or minimal APIs |
54| `web` | Empty ASP.NET Core project |
55| `mvc` | MVC web application |
56| `razor` | Razor Pages application |
57| `blazorserver` | Blazor Server app |
58| `blazorwasm` | Blazor WebAssembly app |
59| `worker` | Background service |
60| `grpc` | gRPC service |
61
62### C# 12 Features (.NET 8+)
63
64| Feature | Example |
65| ------------------------- | --------------------------------------------------- |
66| Primary Constructors | `class Person(string name, int age)` |
67| Collection Expressions | `int[] nums = [1, 2, 3];` |
68| Alias Any Type | `using Point = (int X, int Y);` |
69| Default Lambda Parameters | `var add = (int a, int b = 1) => a + b;` |
70| Inline Arrays | `[InlineArray(10)] struct Buffer { int _element; }` |
71
72---
73
74## 🚀 Project Setup
75
76### Solution Structure
77
78```
79MySolution/
80├── src/
81│ ├── MyApp.Api/ # Web API project
82│ │ ├── Controllers/
83│ │ ├── Endpoints/ # Minimal API endpoints
84│ │ ├── Middleware/
85│ │ ├── Program.cs
86│ │ └── appsettings.json
87│ ├── MyApp.Core/ # Domain/business logic
88│ │ ├── Entities/
89│ │ ├── Interfaces/
90│ │ └── Services/
91│ ├── MyApp.Infrastructure/ # Data access, external services
92│ │ ├── Data/
93│ │ ├── Repositories/
94│ │ └── Services/
95│ └── MyApp.Shared/ # Shared DTOs, utilities
96│ ├── DTOs/
97│ └── Extensions/
98├── tests/
99│ ├── MyApp.UnitTests/
100│ ├── MyApp.IntegrationTests/
101│ └── MyApp.FunctionalTests/
102├── Directory.Build.props # Shared build properties
103├── Directory.Packages.props # Central package management
104└── MySolution.sln
105```
106
107### Directory.Build.props
108
109```xml
110<Project>
111 <PropertyGroup>
112 <TargetFramework>net8.0</TargetFramework>
113 <Nullable>enable</Nullable>
114 <ImplicitUsings>enable</ImplicitUsings>
115 <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
116 <AnalysisLevel>latest-recommended</AnalysisLevel>
117 </PropertyGroup>
118</Project>
119```
120
121### Central Package Management (Directory.Packages.props)
122
123```xml
124<Project>
125 <PropertyGroup>
126 <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
127 </PropertyGroup>
128 <ItemGroup>
129 <PackageVersion Include="Microsoft.EntityFrameworkCore" Version="8.0.0" />
130 <PackageVersion Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.0" />
131 <PackageVersion Include="Swashbuckle.AspNetCore" Version="6.5.0" />
132 <PackageVersion Include="FluentValidation" Version="11.9.0" />
133 <PackageVersion Include="Serilog.AspNetCore" Version="8.0.0" />
134 <PackageVersion Include="xunit" Version="2.6.4" />
135 <PackageVersion Include="Moq" Version="4.20.70" />
136 </ItemGroup>
137</Project>
138```
139
140---
141
142## 🌐 ASP.NET Core
143
144### Program.cs (Modern Setup)
145
146```csharp
147using MyApp.Api.Middleware;
148using MyApp.Core.Interfaces;
149using MyApp.Infrastructure.Data;
150using MyApp.Infrastructure.Services;
151
152var builder = WebApplication.CreateBuilder(args);
153
154// Configuration
155builder.Configuration
156 .AddJsonFile("appsettings.json", optional: false)
157 .AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true)
158 .AddEnvironmentVariables()
159 .AddUserSecrets<Program>(optional: true);
160
161// Services
162builder.Services.AddControllers();
163builder.Services.AddEndpointsApiExplorer();
164builder.Services.AddSwaggerGen();
165
166// Database
167builder.Services.AddDbContext<AppDbContext>(options =>
168 options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
169
170// Application services
171builder.Services.AddScoped<IUserService, UserService>();
172builder.Services.AddScoped<IEmailService, EmailService>();
173
174// Health checks
175builder.Services.AddHealthChecks()
176 .AddDbContextCheck<AppDbContext>();
177
178var app = builder.Build();
179
180// Middleware pipeline
181if (app.Environment.IsDevelopment())
182{
183 app.UseSwagger();
184 app.UseSwaggerUI();
185}
186
187app.UseHttpsRedirection();
188app.UseAuthentication();
189app.UseAuthorization();
190
191app.UseMiddleware<ExceptionHandlingMiddleware>();
192
193app.MapControllers();
194app.MapHealthChecks("/health");
195
196app.Run();
197
198// Make Program class accessible for integration tests
199public partial class Program { }
200```
201
202### Controller Pattern
203
204```csharp
205using Microsoft.AspNetCore.Mvc;
206
207namespace MyApp.Api.Controllers;
208
209[ApiController]
210[Route("api/[controller]")]
211[Produces("application/json")]
212public class UsersController : ControllerBase
213{
214 private readonly IUserService _userService;
215 private readonly ILogger<UsersController> _logger;
216
217 public UsersController(IUserService userService, ILogger<UsersController> logger)
218 {
219 _userService = userService;
220 _logger = logger;
221 }
222
223 /// <summary>
224 /// Gets all users with optional filtering
225 /// </summary>
226 [HttpGet]
227 [ProducesResponseType(typeof(IEnumerable<UserDto>), StatusCodes.Status200OK)]
228 public async Task<ActionResult<IEnumerable<UserDto>>> GetUsers(
229 [FromQuery] string? search = null,
230 [FromQuery] int page = 1,
231 [FromQuery] int pageSize = 10,
232 CancellationToken cancellationToken = default)
233 {
234 var users = await _userService.GetUsersAsync(search, page, pageSize, cancellationToken);
235 return Ok(users);
236 }
237
238 /// <summary>
239 /// Gets a specific user by ID
240 /// </summary>
241 [HttpGet("{id:guid}")]
242 [ProducesResponseType(typeof(UserDto), StatusCodes.Status200OK)]
243 [ProducesResponseType(StatusCodes.Status404NotFound)]
244 public async Task<ActionResult<UserDto>> GetUser(
245 Guid id,
246 CancellationToken cancellationToken = default)
247 {
248 var user = await _userService.GetByIdAsync(id, cancellationToken);
249
250 if (user is null)
251 {
252 return NotFound();
253 }
254
255 return Ok(user);
256 }
257
258 /// <summary>
259 /// Creates a new user
260 /// </summary>
261 [HttpPost]
262 [ProducesResponseType(typeof(UserDto), StatusCodes.Status201Created)]
263 [ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)]
264 public async Task<ActionResult<UserDto>> CreateUser(
265 [FromBody] CreateUserRequest request,
266 CancellationToken cancellationToken = default)
267 {
268 var user = await _userService.CreateAsync(request, cancellationToken);
269
270 _logger.LogInformation("Created user {UserId}", user.Id);
271
272 return CreatedAtAction(
273 nameof(GetUser),
274 new { id = user.Id },
275 user);
276 }
277
278 /// <summary>
279 /// Updates an existing user
280 /// </summary>
281 [HttpPut("{id:guid}")]
282 [ProducesResponseType(typeof(UserDto), StatusCodes.Status200OK)]
283 [ProducesResponseType(StatusCodes.Status404NotFound)]
284 public async Task<ActionResult<UserDto>> UpdateUser(
285 Guid id,
286 [FromBody] UpdateUserRequest request,
287 CancellationToken cancellationToken = default)
288 {
289 var user = await _userService.UpdateAsync(id, request, cancellationToken);
290
291 if (user is null)
292 {
293 return NotFound();
294 }
295
296 return Ok(user);
297 }
298
299 /// <summary>
300 /// Deletes a user
301 /// </summary>
302 [HttpDelete("{id:guid}")]
303 [ProducesResponseType(StatusCodes.Status204NoContent)]
304 [ProducesResponseType(StatusCodes.Status404NotFound)]
305 public async Task<IActionResult> DeleteUser(
306 Guid id,
307 CancellationToken cancellationToken = default)
308 {
309 var deleted = await _userService.DeleteAsync(id, cancellationToken);
310
311 if (!deleted)
312 {
313 return NotFound();
314 }
315
316 return NoContent();
317 }
318}
319```
320
321---
322
323## ⚡ Minimal APIs
324
325### Basic Setup
326
327```csharp
328var builder = WebApplication.CreateBuilder(args);
329
330builder.Services.AddEndpointsApiExplorer();
331builder.Services.AddSwaggerGen();
332builder.Services.AddScoped<IUserService, UserService>();
333
334var app = builder.Build();
335
336if (app.Environment.IsDevelopment())
337{
338 app.UseSwagger();
339 app.UseSwaggerUI();
340}
341
342// Map endpoints
343app.MapUserEndpoints();
344app.MapProductEndpoints();
345
346app.Run();
347```
348
349### Organized Endpoints
350
351```csharp
352namespace MyApp.Api.Endpoints;
353
354public static class UserEndpoints
355{
356 public static void MapUserEndpoints(this IEndpointRouteBuilder routes)
357 {
358 var group = routes.MapGroup("/api/users")
359 .WithTags("Users")
360 .WithOpenApi();
361
362 group.MapGet("/", GetUsers)
363 .WithName("GetUsers")
364 .WithSummary("Gets all users");
365
366 group.MapGet("/{id:guid}", GetUserById)
367 .WithName("GetUserById")
368 .WithSummary("Gets a user by ID");
369
370 group.MapPost("/", CreateUser)
371 .WithName("CreateUser")
372 .WithSummary("Creates a new user")
373 .AddEndpointFilter<ValidationFilter<CreateUserRequest>>();
374
375 group.MapPut("/{id:guid}", UpdateUser)
376 .WithName("UpdateUser")
377 .RequireAuthorization();
378
379 group.MapDelete("/{id:guid}", DeleteUser)
380 .WithName("DeleteUser")
381 .RequireAuthorization("AdminOnly");
382 }
383
384 private static async Task<IResult> GetUsers(
385 IUserService userService,
386 [AsParameters] PaginationQuery pagination,
387 CancellationToken cancellationToken)
388 {
389 var users = await userService.GetUsersAsync(
390 pagination.Page,
391 pagination.PageSize,
392 cancellationToken);
393
394 return Results.Ok(users);
395 }
396
397 private static async Task<IResult> GetUserById(
398 Guid id,
399 IUserService userService,
400 CancellationToken cancellationToken)
401 {
402 var user = await userService.GetByIdAsync(id, cancellationToken);
403
404 return user is null
405 ? Results.NotFound()
406 : Results.Ok(user);
407 }
408
409 private static async Task<IResult> CreateUser(
410 CreateUserRequest request,
411 IUserService userService,
412 CancellationToken cancellationToken)
413 {
414 var user = await userService.CreateAsync(request, cancellationToken);
415
416 return Results.CreatedAtRoute(
417 "GetUserById",
418 new { id = user.Id },
419 user);
420 }
421
422 private static async Task<IResult> UpdateUser(
423 Guid id,
424 UpdateUserRequest request,
425 IUserService userService,
426 CancellationToken cancellationToken)
427 {
428 var user = await userService.UpdateAsync(id, request, cancellationToken);
429
430 return user is null
431 ? Results.NotFound()
432 : Results.Ok(user);
433 }
434
435 private static async Task<IResult> DeleteUser(
436 Guid id,
437 IUserService userService,
438 CancellationToken cancellationToken)
439 {
440 var deleted = await userService.DeleteAsync(id, cancellationToken);
441
442 return deleted
443 ? Results.NoContent()
444 : Results.NotFound();
445 }
446}
447
448// Parameter binding class
449public record PaginationQuery(
450 [FromQuery] int Page = 1,
451 [FromQuery] int PageSize = 10);
452```
453
454### Typed Results (Better OpenAPI)
455
456```csharp
457public static class UserEndpoints
458{
459 public static void MapUserEndpoints(this IEndpointRouteBuilder routes)
460 {
461 routes.MapGet("/api/users/{id:guid}", GetUserById);
462 }
463
464 private static async Task<Results<Ok<UserDto>, NotFound>> GetUserById(
465 Guid id,
466 IUserService userService,
467 CancellationToken cancellationToken)
468 {
469 var user = await userService.GetByIdAsync(id, cancellationToken);
470
471 return user is null
472 ? TypedResults.NotFound()
473 : TypedResults.Ok(user);
474 }
475}
476```
477
478---
479
480## 🗄️ Entity Framework Core
481
482### DbContext
483
484```csharp
485using Microsoft.EntityFrameworkCore;
486
487namespace MyApp.Infrastructure.Data;
488
489public class AppDbContext : DbContext
490{
491 public AppDbContext(DbContextOptions<AppDbContext> options)
492 : base(options)
493 {
494 }
495
496 public DbSet<User> Users => Set<User>();
497 public DbSet<Order> Orders => Set<Order>();
498 public DbSet<Product> Products => Set<Product>();
499
500 protected override void OnModelCreating(ModelBuilder modelBuilder)
501 {
502 // Apply all configurations from assembly
503 modelBuilder.ApplyConfigurationsFromAssembly(
504 typeof(AppDbContext).Assembly);
505
506 // Global query filters
507 modelBuilder.Entity<User>()
508 .HasQueryFilter(u => !u.IsDeleted);
509
510 base.OnModelCreating(modelBuilder);
511 }
512
513 public override async Task<int> SaveChangesAsync(
514 CancellationToken cancellationToken = default)
515 {
516 // Audit trail
517 foreach (var entry in ChangeTracker.Entries<IAuditable>())
518 {
519 switch (entry.State)
520 {
521 case EntityState.Added:
522 entry.Entity.CreatedAt = DateTime.UtcNow;
523 break;
524 case EntityState.Modified:
525 entry.Entity.UpdatedAt = DateTime.UtcNow;
526 break;
527 }
528 }
529
530 return await base.SaveChangesAsync(cancellationToken);
531 }
532}
533```
534
535### Entity Configuration
536
537```csharp
538using Microsoft.EntityFrameworkCore;
539using Microsoft.EntityFrameworkCore.Metadata.Builders;
540
541namespace MyApp.Infrastructure.Data.Configurations;
542
543public class UserConfiguration : IEntityTypeConfiguration<User>
544{
545 public void Configure(EntityTypeBuilder<User> builder)
546 {
547 builder.ToTable("Users");
548
549 builder.HasKey(u => u.Id);
550
551 builder.Property(u => u.Id)
552 .ValueGeneratedOnAdd();
553
554 builder.Property(u => u.Email)
555 .IsRequired()
556 .HasMaxLength(256);
557
558 builder.Property(u => u.FirstName)
559 .IsRequired()
560 .HasMaxLength(100);
561
562 builder.Property(u => u.LastName)
563 .IsRequired()
564 .HasMaxLength(100);
565
566 builder.Property(u => u.PasswordHash)
567 .IsRequired();
568
569 // Indexes
570 builder.HasIndex(u => u.Email)
571 .IsUnique();
572
573 // Relationships
574 builder.HasMany(u => u.Orders)
575 .WithOne(o => o.User)
576 .HasForeignKey(o => o.UserId)
577 .OnDelete(DeleteBehavior.Cascade);
578
579 // Value objects
580 builder.OwnsOne(u => u.Address, address =>
581 {
582 address.Property(a => a.Street).HasMaxLength(200);
583 address.Property(a => a.City).HasMaxLength(100);
584 address.Property(a => a.ZipCode).HasMaxLength(20);
585 address.Property(a => a.Country).HasMaxLength(100);
586 });
587
588 // Seed data
589 builder.HasData(
590 new User
591 {
592 Id = Guid.Parse("11111111-1111-1111-1111-111111111111"),
593 Email = "admin@example.com",
594 FirstName = "Admin",
595 LastName = "User"
596 });
597 }
598}
599```
600
601### Repository Pattern
602
603```csharp
604namespace MyApp.Core.Interfaces;
605
606public interface IRepository<T> where T : class
607{
608 Task<T?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default);
609 Task<IReadOnlyList<T>> GetAllAsync(CancellationToken cancellationToken = default);
610 Task<T> AddAsync(T entity, CancellationToken cancellationToken = default);
611 Task UpdateAsync(T entity, CancellationToken cancellationToken = default);
612 Task DeleteAsync(T entity, CancellationToken cancellationToken = default);
613}
614
615public interface IUserRepository : IRepository<User>
616{
617 Task<User?> GetByEmailAsync(string email, CancellationToken cancellationToken = default);
618 Task<IReadOnlyList<User>> GetActiveUsersAsync(CancellationToken cancellationToken = default);
619}
620```
621
622```csharp
623namespace MyApp.Infrastructure.Repositories;
624
625public class Repository<T> : IRepository<T> where T : class
626{
627 protected readonly AppDbContext _context;
628 protected readonly DbSet<T> _dbSet;
629
630 public Repository(AppDbContext context)
631 {
632 _context = context;
633 _dbSet = context.Set<T>();
634 }
635
636 public virtual async Task<T?> GetByIdAsync(
637 Guid id,
638 CancellationToken cancellationToken = default)
639 {
640 return await _dbSet.FindAsync([id], cancellationToken);
641 }
642
643 public virtual async Task<IReadOnlyList<T>> GetAllAsync(
644 CancellationToken cancellationToken = default)
645 {
646 return await _dbSet.ToListAsync(cancellationToken);
647 }
648
649 public virtual async Task<T> AddAsync(
650 T entity,
651 CancellationToken cancellationToken = default)
652 {
653 await _dbSet.AddAsync(entity, cancellationToken);
654 await _context.SaveChangesAsync(cancellationToken);
655 return entity;
656 }
657
658 public virtual async Task UpdateAsync(
659 T entity,
660 CancellationToken cancellationToken = default)
661 {
662 _dbSet.Update(entity);
663 await _context.SaveChangesAsync(cancellationToken);
664 }
665
666 public virtual async Task DeleteAsync(
667 T entity,
668 CancellationToken cancellationToken = default)
669 {
670 _dbSet.Remove(entity);
671 await _context.SaveChangesAsync(cancellationToken);
672 }
673}
674
675public class UserRepository : Repository<User>, IUserRepository
676{
677 public UserRepository(AppDbContext context) : base(context)
678 {
679 }
680
681 public async Task<User?> GetByEmailAsync(
682 string email,
683 CancellationToken cancellationToken = default)
684 {
685 return await _dbSet
686 .FirstOrDefaultAsync(u => u.Email == email, cancellationToken);
687 }
688
689 public async Task<IReadOnlyList<User>> GetActiveUsersAsync(
690 CancellationToken cancellationToken = default)
691 {
692 return await _dbSet
693 .Where(u => u.IsActive)
694 .OrderBy(u => u.LastName)
695 .ThenBy(u => u.FirstName)
696 .ToListAsync(cancellationToken);
697 }
698}
699```
700
701### Specification Pattern
702
703```csharp
704namespace MyApp.Core.Specifications;
705
706public abstract class Specification<T>
707{
708 public abstract Expression<Func<T, bool>> ToExpression();
709
710 public bool IsSatisfiedBy(T entity)
711 {
712 var predicate = ToExpression().Compile();
713 return predicate(entity);
714 }
715
716 public Specification<T> And(Specification<T> specification)
717 {
718 return new AndSpecification<T>(this, specification);
719 }
720
721 public Specification<T> Or(Specification<T> specification)
722 {
723 return new OrSpecification<T>(this, specification);
724 }
725}
726
727public class ActiveUserSpecification : Specification<User>
728{
729 public override Expression<Func<User, bool>> ToExpression()
730 {
731 return user => user.IsActive && !user.IsDeleted;
732 }
733}
734
735public class UserByEmailSpecification : Specification<User>
736{
737 private readonly string _email;
738
739 public UserByEmailSpecification(string email)
740 {
741 _email = email;
742 }
743
744 public override Expression<Func<User, bool>> ToExpression()
745 {
746 return user => user.Email == _email;
747 }
748}
749```
750
751---
752
753## 💉 Dependency Injection
754
755### Service Registration
756
757```csharp
758namespace MyApp.Api.Extensions;
759
760public static class ServiceCollectionExtensions
761{
762 public static IServiceCollection AddApplicationServices(
763 this IServiceCollection services)
764 {
765 // Transient - new instance every time
766 services.AddTransient<IEmailService, EmailService>();
767
768 // Scoped - one instance per request
769 services.AddScoped<IUserService, UserService>();
770 services.AddScoped<IOrderService, OrderService>();
771 services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
772
773 // Singleton - one instance for app lifetime
774 services.AddSingleton<ICacheService, MemoryCacheService>();
775
776 return services;
777 }
778
779 public static IServiceCollection AddInfrastructure(
780 this IServiceCollection services,
781 IConfiguration configuration)
782 {
783 // Database
784 services.AddDbContext<AppDbContext>(options =>
785 options.UseSqlServer(
786 configuration.GetConnectionString("DefaultConnection"),
787 sqlOptions =>
788 {
789 sqlOptions.EnableRetryOnFailure(
790 maxRetryCount: 3,
791 maxRetryDelay: TimeSpan.FromSeconds(30),
792 errorNumbersToAdd: null);
793 sqlOptions.CommandTimeout(30);
794 }));
795
796 // Repositories
797 services.AddScoped<IUserRepository, UserRepository>();
798 services.AddScoped<IOrderRepository, OrderRepository>();
799
800 // HTTP clients
801 services.AddHttpClient<IExternalApiClient, ExternalApiClient>(client =>
802 {
803 client.BaseAddress = new Uri(configuration["ExternalApi:BaseUrl"]!);
804 client.Timeout = TimeSpan.FromSeconds(30);
805 })
806 .AddPolicyHandler(GetRetryPolicy())
807 .AddPolicyHandler(GetCircuitBreakerPolicy());
808
809 return services;
810 }
811
812 private static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
813 {
814 return HttpPolicyExtensions
815 .HandleTransientHttpError()
816 .WaitAndRetryAsync(3, retryAttempt =>
817 TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
818 }
819
820 private static IAsyncPolicy<HttpResponseMessage> GetCircuitBreakerPolicy()
821 {
822 return HttpPolicyExtensions
823 .HandleTransientHttpError()
824 .CircuitBreakerAsync(5, TimeSpan.FromSeconds(30));
825 }
826}
827```
828
829### Keyed Services (.NET 8+)
830
831```csharp
832// Registration
833services.AddKeyedScoped<INotificationService, EmailNotificationService>("email");
834services.AddKeyedScoped<INotificationService, SmsNotificationService>("sms");
835services.AddKeyedScoped<INotificationService, PushNotificationService>("push");
836
837// Injection
838public class NotificationController : ControllerBase
839{
840 public NotificationController(
841 [FromKeyedServices("email")] INotificationService emailService,
842 [FromKeyedServices("sms")] INotificationService smsService)
843 {
844 // Use specific implementations
845 }
846}
847```
848
849### Factory Pattern
850
851```csharp
852public interface IPaymentProcessorFactory
853{
854 IPaymentProcessor Create(PaymentMethod method);
855}
856
857public class PaymentProcessorFactory : IPaymentProcessorFactory
858{
859 private readonly IServiceProvider _serviceProvider;
860
861 public PaymentProcessorFactory(IServiceProvider serviceProvider)
862 {
863 _serviceProvider = serviceProvider;
864 }
865
866 public IPaymentProcessor Create(PaymentMethod method)
867 {
868 return method switch
869 {
870 PaymentMethod.CreditCard => _serviceProvider
871 .GetRequiredService<CreditCardProcessor>(),
872 PaymentMethod.PayPal => _serviceProvider
873 .GetRequiredService<PayPalProcessor>(),
874 PaymentMethod.BankTransfer => _serviceProvider
875 .GetRequiredService<BankTransferProcessor>(),
876 _ => throw new ArgumentException($"Unknown payment method: {method}")
877 };
878 }
879}
880
881// Registration
882services.AddScoped<IPaymentProcessorFactory, PaymentProcessorFactory>();
883services.AddScoped<CreditCardProcessor>();
884services.AddScoped<PayPalProcessor>();
885services.AddScoped<BankTransferProcessor>();
886```
887
888---
889
890## ⚙️ Configuration & Options
891
892### appsettings.json Structure
893
894```json
895{
896 "ConnectionStrings": {
897 "DefaultConnection": "Server=localhost;Database=MyApp;Trusted_Connection=true;",
898 "Redis": "localhost:6379"
899 },
900 "Jwt": {
901 "Secret": "your-secret-key-here",
902 "Issuer": "MyApp",
903 "Audience": "MyApp",
904 "ExpirationMinutes": 60
905 },
906 "Email": {
907 "SmtpServer": "smtp.example.com",
908 "Port": 587,
909 "UseSsl": true,
910 "FromAddress": "noreply@example.com",
911 "FromName": "MyApp"
912 },
913 "Features": {
914 "EnableNewDashboard": true,
915 "MaxUploadSizeMb": 10
916 },
917 "Logging": {
918 "LogLevel": {
919 "Default": "Information",
920 "Microsoft.AspNetCore": "Warning",
921 "Microsoft.EntityFrameworkCore": "Warning"
922 }
923 }
924}
925```
926
927### Options Pattern
928
929```csharp
930namespace MyApp.Core.Options;
931
932public class JwtOptions
933{
934 public const string SectionName = "Jwt";
935
936 public string Secret { get; set; } = string.Empty;
937 public string Issuer { get; set; } = string.Empty;
938 public string Audience { get; set; } = string.Empty;
939 public int ExpirationMinutes { get; set; } = 60;
940}
941
942public class EmailOptions
943{
944 public const string SectionName = "Email";
945
946 public string SmtpServer { get; set; } = string.Empty;
947 public int Port { get; set; } = 587;
948 public bool UseSsl { get; set; } = true;
949 public string FromAddress { get; set; } = string.Empty;
950 public string FromName { get; set; } = string.Empty;
951}
952```
953
954### Options Validation
955
956```csharp
957public class JwtOptionsValidator : IValidateOptions<JwtOptions>
958{
959 public ValidateOptionsResult Validate(string? name, JwtOptions options)
960 {
961 var failures = new List<string>();
962
963 if (string.IsNullOrWhiteSpace(options.Secret))
964 {
965 failures.Add("JWT Secret is required");
966 }
967 else if (options.Secret.Length < 32)
968 {
969 failures.Add("JWT Secret must be at least 32 characters");
970 }
971
972 if (string.IsNullOrWhiteSpace(options.Issuer))
973 {
974 failures.Add("JWT Issuer is required");
975 }
976
977 if (options.ExpirationMinutes <= 0)
978 {
979 failures.Add("JWT ExpirationMinutes must be positive");
980 }
981
982 return failures.Count > 0
983 ? ValidateOptionsResult.Fail(failures)
984 : ValidateOptionsResult.Success;
985 }
986}
987
988// Registration
989services.AddOptions<JwtOptions>()
990 .Bind(configuration.GetSection(JwtOptions.SectionName))
991 .ValidateDataAnnotations()
992 .ValidateOnStart();
993
994services.AddSingleton<IValidateOptions<JwtOptions>, JwtOptionsValidator>();
995```
996
997### Using Options
998
999```csharp
1000public class TokenService : ITokenService
1001{
1002 private readonly JwtOptions _jwtOptions;
1003
1004 // Use IOptions for singleton-scoped options
1005 public TokenService(IOptions<JwtOptions> jwtOptions)
1006 {
1007 _jwtOptions = jwtOptions.Value;
1008 }
1009
1010 // Use IOptionsSnapshot for scoped options (reloads on change)
1011 public TokenService(IOptionsSnapshot<JwtOptions> jwtOptions)
1012 {
1013 _jwtOptions = jwtOptions.Value;
1014 }
1015
1016 // Use IOptionsMonitor for singleton services that need to react to changes
1017 public TokenService(IOptionsMonitor<JwtOptions> jwtOptions)
1018 {
1019 _jwtOptions = jwtOptions.CurrentValue;
1020 jwtOptions.OnChange(newOptions =>
1021 {
1022 // React to configuration changes
1023 });
1024 }
1025}
1026```
1027
1028---
1029
1030## 🔧 Middleware & Filters
1031
1032### Custom Middleware
1033
1034```csharp
1035namespace MyApp.Api.Middleware;
1036
1037public class ExceptionHandlingMiddleware
1038{
1039 private readonly RequestDelegate _next;
1040 private readonly ILogger<ExceptionHandlingMiddleware> _logger;
1041
1042 public ExceptionHandlingMiddleware(
1043 RequestDelegate next,
1044 ILogger<ExceptionHandlingMiddleware> logger)
1045 {
1046 _next = next;
1047 _logger = logger;
1048 }
1049
1050 public async Task InvokeAsync(HttpContext context)
1051 {
1052 try
1053 {
1054 await _next(context);
1055 }
1056 catch (Exception ex)
1057 {
1058 await HandleExceptionAsync(context, ex);
1059 }
1060 }
1061
1062 private async Task HandleExceptionAsync(HttpContext context, Exception exception)
1063 {
1064 _logger.LogError(exception, "An unhandled exception occurred");
1065
1066 var (statusCode, message) = exception switch
1067 {
1068 NotFoundException => (StatusCodes.Status404NotFound, exception.Message),
1069 ValidationException validationEx => (
1070 StatusCodes.Status400BadRequest,
1071 string.Join("; ", validationEx.Errors)),
1072 UnauthorizedAccessException => (
1073 StatusCodes.Status401Unauthorized,
1074 "Unauthorized"),
1075 ForbiddenException => (
1076 StatusCodes.Status403Forbidden,
1077 "Forbidden"),
1078 _ => (
1079 StatusCodes.Status500InternalServerError,
1080 "An error occurred processing your request")
1081 };
1082
1083 context.Response.StatusCode = statusCode;
1084 context.Response.ContentType = "application/problem+json";
1085
1086 var problemDetails = new ProblemDetails
1087 {
1088 Status = statusCode,
1089 Title = GetTitle(statusCode),
1090 Detail = message,
1091 Instance = context.Request.Path
1092 };
1093
1094 await context.Response.WriteAsJsonAsync(problemDetails);
1095 }
1096
1097 private static string GetTitle(int statusCode) => statusCode switch
1098 {
1099 400 => "Bad Request",
1100 401 => "Unauthorized",
1101 403 => "Forbidden",
1102 404 => "Not Found",
1103 _ => "Server Error"
1104 };
1105}
1106
1107// Extension method
1108public static class MiddlewareExtensions
1109{
1110 public static IApplicationBuilder UseExceptionHandling(
1111 this IApplicationBuilder app)
1112 {
1113 return app.UseMiddleware<ExceptionHandlingMiddleware>();
1114 }
1115}
1116```
1117
1118### Request Logging Middleware
1119
1120```csharp
1121public class RequestLoggingMiddleware
1122{
1123 private readonly RequestDelegate _next;
1124 private readonly ILogger<RequestLoggingMiddleware> _logger;
1125
1126 public RequestLoggingMiddleware(
1127 RequestDelegate next,
1128 ILogger<RequestLoggingMiddleware> logger)
1129 {
1130 _next = next;
1131 _logger = logger;
1132 }
1133
1134 public async Task InvokeAsync(HttpContext context)
1135 {
1136 var stopwatch = Stopwatch.StartNew();
1137 var requestId = Activity.Current?.Id ?? context.TraceIdentifier;
1138
1139 _logger.LogInformation(
1140 "Request started: {Method} {Path} [{RequestId}]",
1141 context.Request.Method,
1142 context.Request.Path,
1143 requestId);
1144
1145 try
1146 {
1147 await _next(context);
1148 }
1149 finally
1150 {
1151 stopwatch.Stop();
1152
1153 _logger.LogInformation(
1154 "Request completed: {Method} {Path} [{RequestId}] - {StatusCode} in {ElapsedMs}ms",
1155 context.Request.Method,
1156 context.Request.Path,
1157 requestId,
1158 context.Response.StatusCode,
1159 stopwatch.ElapsedMilliseconds);
1160 }
1161 }
1162}
1163```
1164
1165### Action Filters
1166
1167```csharp
1168namespace MyApp.Api.Filters;
1169
1170public class ValidationFilter : IAsyncActionFilter
1171{
1172 public async Task OnActionExecutionAsync(
1173 ActionExecutingContext context,
1174 ActionExecutionDelegate next)
1175 {
1176 if (!context.ModelState.IsValid)
1177 {
1178 var errors = context.ModelState
1179 .Where(x => x.Value?.Errors.Count > 0)
1180 .ToDictionary(
1181 x => x.Key,
1182 x => x.Value!.Errors.Select(e => e.ErrorMessage).ToArray());
1183
1184 context.Result = new BadRequestObjectResult(
1185 new ValidationProblemDetails(context.ModelState));
1186 return;
1187 }
1188
1189 await next();
1190 }
1191}
1192
1193// Minimal API filter
1194public class ValidationFilter<T> : IEndpointFilter where T : class
1195{
1196 public async ValueTask<object?> InvokeAsync(
1197 EndpointFilterInvocationContext context,
1198 EndpointFilterDelegate next)
1199 {
1200 var validator = context.HttpContext.RequestServices
1201 .GetService<IValidator<T>>();
1202
1203 if (validator is null)
1204 {
1205 return await next(context);
1206 }
1207
1208 var argument = context.Arguments
1209 .OfType<T>()
1210 .FirstOrDefault();
1211
1212 if (argument is null)
1213 {
1214 return await next(context);
1215 }
1216
1217 var validationResult = await validator.ValidateAsync(argument);
1218
1219 if (!validationResult.IsValid)
1220 {
1221 return Results.ValidationProblem(
1222 validationResult.ToDictionary());
1223 }
1224
1225 return await next(context);
1226 }
1227}
1228```
1229
1230### Exception Filter
1231
1232```csharp
1233public class GlobalExceptionFilter : IExceptionFilter
1234{
1235 private readonly ILogger<GlobalExceptionFilter> _logger;
1236 private readonly IHostEnvironment _environment;
1237
1238 public GlobalExceptionFilter(
1239 ILogger<GlobalExceptionFilter> logger,
1240 IHostEnvironment environment)
1241 {
1242 _logger = logger;
1243 _environment = environment;
1244 }
1245
1246 public void OnException(ExceptionContext context)
1247 {
1248 _logger.LogError(context.Exception, "Unhandled exception occurred");
1249
1250 var problemDetails = new ProblemDetails
1251 {
1252 Status = StatusCodes.Status500InternalServerError,
1253 Title = "An error occurred",
1254 Detail = _environment.IsDevelopment()
1255 ? context.Exception.Message
1256 : "An error occurred processing your request"
1257 };
1258
1259 context.Result = new ObjectResult(problemDetails)
1260 {
1261 StatusCode = StatusCodes.Status500InternalServerError
1262 };
1263
1264 context.ExceptionHandled = true;
1265 }
1266}
1267
1268// Registration
1269services.AddControllers(options =>
1270{
1271 options.Filters.Add<GlobalExceptionFilter>();
1272});
1273```
1274
1275---
1276
1277## 🔐 Authentication & Authorization
1278
1279### JWT Authentication
1280
1281```csharp
1282using Microsoft.AspNetCore.Authentication.JwtBearer;
1283using Microsoft.IdentityModel.Tokens;
1284
1285public static class AuthenticationExtensions
1286{
1287 public static IServiceCollection AddJwtAuthentication(
1288 this IServiceCollection services,
1289 IConfiguration configuration)
1290 {
1291 var jwtOptions = configuration
1292 .GetSection(JwtOptions.SectionName)
1293 .Get<JwtOptions>()!;
1294
1295 services.AddAuthentication(options =>
1296 {
1297 options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
1298 options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
1299 })
1300 .AddJwtBearer(options =>
1301 {
1302 options.TokenValidationParameters = new TokenValidationParameters
1303 {
1304 ValidateIssuer = true,
1305 ValidateAudience = true,
1306 ValidateLifetime = true,
1307 ValidateIssuerSigningKey = true,
1308 ValidIssuer = jwtOptions.Issuer,
1309 ValidAudience = jwtOptions.Audience,
1310 IssuerSigningKey = new SymmetricSecurityKey(
1311 Encoding.UTF8.GetBytes(jwtOptions.Secret)),
1312 ClockSkew = TimeSpan.Zero
1313 };
1314
1315 options.Events = new JwtBearerEvents
1316 {
1317 OnAuthenticationFailed = context =>
1318 {
1319 if (context.Exception is SecurityTokenExpiredException)
1320 {
1321 context.Response.Headers.Append(
1322 "Token-Expired", "true");
1323 }
1324 return Task.CompletedTask;
1325 }
1326 };
1327 });
1328
1329 return services;
1330 }
1331}
1332```
1333
1334### Token Service
1335
1336```csharp
1337public interface ITokenService
1338{
1339 string GenerateAccessToken(User user);
1340 string GenerateRefreshToken();
1341 ClaimsPrincipal? ValidateToken(string token);
1342}
1343
1344public class TokenService : ITokenService
1345{
1346 private readonly JwtOptions _options;
1347
1348 public TokenService(IOptions<JwtOptions> options)
1349 {
1350 _options = options.Value;
1351 }
1352
1353 public string GenerateAccessToken(User user)
1354 {
1355 var claims = new List<Claim>
1356 {
1357 new(ClaimTypes.NameIdentifier, user.Id.ToString()),
1358 new(ClaimTypes.Email, user.Email),
1359 new(ClaimTypes.Name, $"{user.FirstName} {user.LastName}"),
1360 new("role", user.Role.ToString())
1361 };
1362
1363 var key = new SymmetricSecurityKey(
1364 Encoding.UTF8.GetBytes(_options.Secret));
1365 var credentials = new SigningCredentials(
1366 key, SecurityAlgorithms.HmacSha256);
1367
1368 var token = new JwtSecurityToken(
1369 issuer: _options.Issuer,
1370 audience: _options.Audience,
1371 claims: claims,
1372 expires: DateTime.UtcNow.AddMinutes(_options.ExpirationMinutes),
1373 signingCredentials: credentials);
1374
1375 return new JwtSecurityTokenHandler().WriteToken(token);
1376 }
1377
1378 public string GenerateRefreshToken()
1379 {
1380 var randomBytes = new byte[64];
1381 using var rng = RandomNumberGenerator.Create();
1382 rng.GetBytes(randomBytes);
1383 return Convert.ToBase64String(randomBytes);
1384 }
1385
1386 public ClaimsPrincipal? ValidateToken(string token)
1387 {
1388 var tokenHandler = new JwtSecurityTokenHandler();
1389 var key = Encoding.UTF8.GetBytes(_options.Secret);
1390
1391 try
1392 {
1393 return tokenHandler.ValidateToken(token,
1394 new TokenValidationParameters
1395 {
1396 ValidateIssuerSigningKey = true,
1397 IssuerSigningKey = new SymmetricSecurityKey(key),
1398 ValidateIssuer = true,
1399 ValidIssuer = _options.Issuer,
1400 ValidateAudience = true,
1401 ValidAudience = _options.Audience,
1402 ValidateLifetime = false // Allow expired tokens for refresh
1403 }, out _);
1404 }
1405 catch
1406 {
1407 return null;
1408 }
1409 }
1410}
1411```
1412
1413### Authorization Policies
1414
1415```csharp
1416public static class AuthorizationExtensions
1417{
1418 public static IServiceCollection AddAuthorizationPolicies(
1419 this IServiceCollection services)
1420 {
1421 services.AddAuthorization(options =>
1422 {
1423 // Role-based policies
1424 options.AddPolicy("AdminOnly", policy =>
1425 policy.RequireRole("Admin"));
1426
1427 options.AddPolicy("ManagerOrAdmin", policy =>
1428 policy.RequireRole("Manager", "Admin"));
1429
1430 // Claim-based policies
1431 options.AddPolicy("VerifiedEmail", policy =>
1432 policy.RequireClaim("email_verified", "true"));
1433
1434 // Custom requirement policies
1435 options.AddPolicy("MinimumAge", policy =>
1436 policy.AddRequirements(new MinimumAgeRequirement(18)));
1437
1438 // Resource-based authorization
1439 options.AddPolicy("OwnerOnly", policy =>
1440 policy.AddRequirements(new ResourceOwnerRequirement()));
1441
1442 // Combined policies
1443 options.AddPolicy("PremiumFeature", policy =>
1444 policy.RequireRole("Premium", "Admin")
1445 .RequireClaim("subscription_active", "true"));
1446 });
1447
1448 // Register handlers
1449 services.AddScoped<IAuthorizationHandler, MinimumAgeHandler>();
1450 services.AddScoped<IAuthorizationHandler, ResourceOwnerHandler>();
1451
1452 return services;
1453 }
1454}
1455
1456// Custom requirement
1457public class MinimumAgeRequirement : IAuthorizationRequirement
1458{
1459 public int MinimumAge { get; }
1460
1461 public MinimumAgeRequirement(int minimumAge)
1462 {
1463 MinimumAge = minimumAge;
1464 }
1465}
1466
1467// Custom handler
1468public class MinimumAgeHandler : AuthorizationHandler<MinimumAgeRequirement>
1469{
1470 protected override Task HandleRequirementAsync(
1471 AuthorizationHandlerContext context,
1472 MinimumAgeRequirement requirement)
1473 {
1474 var birthDateClaim = context.User.FindFirst("birthdate");
1475
1476 if (birthDateClaim is null)
1477 {
1478 return Task.CompletedTask;
1479 }
1480
1481 if (DateTime.TryParse(birthDateClaim.Value, out var birthDate))
1482 {
1483 var age = DateTime.Today.Year - birthDate.Year;
1484 if (birthDate > DateTime.Today.AddYears(-age))
1485 {
1486 age--;
1487 }
1488
1489 if (age >= requirement.MinimumAge)
1490 {
1491 context.Succeed(requirement);
1492 }
1493 }
1494
1495 return Task.CompletedTask;
1496 }
1497}
1498```
1499
1500### Resource-Based Authorization
1501
1502```csharp
1503public class DocumentAuthorizationHandler :
1504 AuthorizationHandler<OperationAuthorizationRequirement, Document>
1505{
1506 protected override Task HandleRequirementAsync(
1507 AuthorizationHandlerContext context,
1508 OperationAuthorizationRequirement requirement,
1509 Document resource)
1510 {
1511 var userId = context.User.FindFirstValue(ClaimTypes.NameIdentifier);
1512
1513 if (userId is null)
1514 {
1515 return Task.CompletedTask;
1516 }
1517
1518 // Owner can do anything
1519 if (resource.OwnerId.ToString() == userId)
1520 {
1521 context.Succeed(requirement);
1522 return Task.CompletedTask;
1523 }
1524
1525 // Admins can do anything
1526 if (context.User.IsInRole("Admin"))
1527 {
1528 context.Succeed(requirement);
1529 return Task.CompletedTask;
1530 }
1531
1532 // Check specific operations for shared documents
1533 if (requirement.Name == Operations.Read.Name &&
1534 resource.SharedWith.Contains(Guid.Parse(userId)))
1535 {
1536 context.Succeed(requirement);
1537 }
1538
1539 return Task.CompletedTask;
1540 }
1541}
1542
1543// Usage in controller
1544public class DocumentsController : ControllerBase
1545{
1546 private readonly IAuthorizationService _authorizationService;
1547
1548 [HttpDelete("{id}")]
1549 public async Task<IActionResult> Delete(Guid id)
1550 {
1551 var document = await _documentService.GetByIdAsync(id);
1552
1553 if (document is null)
1554 {
1555 return NotFound();
1556 }
1557
1558 var authResult = await _authorizationService.AuthorizeAsync(
1559 User, document, Operations.Delete);
1560
1561 if (!authResult.Succeeded)
1562 {
1563 return Forbid();
1564 }
1565
1566 await _documentService.DeleteAsync(id);
1567 return NoContent();
1568 }
1569}
1570```
1571
1572---
1573
1574## ⚡ Background Services
1575
1576### Hosted Service
1577
1578```csharp
1579namespace MyApp.Api.Services;
1580
1581public class CleanupBackgroundService : BackgroundService
1582{
1583 private readonly IServiceScopeFactory _scopeFactory;
1584 private readonly ILogger<CleanupBackgroundService> _logger;
1585 private readonly TimeSpan _period = TimeSpan.FromHours(1);
1586
1587 public CleanupBackgroundService(
1588 IServiceScopeFactory scopeFactory,
1589 ILogger<CleanupBackgroundService> logger)
1590 {
1591 _scopeFactory = scopeFactory;
1592 _logger = logger;
1593 }
1594
1595 protected override async Task ExecuteAsync(CancellationToken stoppingToken)
1596 {
1597 _logger.LogInformation("Cleanup service starting");
1598
1599 using var timer = new PeriodicTimer(_period);
1600
1601 while (!stoppingToken.IsCancellationRequested &&
1602 await timer.WaitForNextTickAsync(stoppingToken))
1603 {
1604 try
1605 {
1606 await DoCleanupAsync(stoppingToken);
1607 }
1608 catch (Exception ex)
1609 {
1610 _logger.LogError(ex, "Error during cleanup");
1611 }
1612 }
1613 }
1614
1615 private async Task DoCleanupAsync(CancellationToken stoppingToken)
1616 {
1617 _logger.LogInformation("Starting cleanup task");
1618
1619 using var scope = _scopeFactory.CreateScope();
1620 var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
1621
1622 var cutoffDate = DateTime.UtcNow.AddDays(-30);
1623
1624 var deletedCount = await dbContext.AuditLogs
1625 .Where(l => l.CreatedAt < cutoffDate)
1626 .ExecuteDeleteAsync(stoppingToken);
1627
1628 _logger.LogInformation("Deleted {Count} old audit logs", deletedCount);
1629 }
1630
1631 public override async Task StopAsync(CancellationToken cancellationToken)
1632 {
1633 _logger.LogInformation("Cleanup service stopping");
1634 await base.StopAsync(cancellationToken);
1635 }
1636}
1637
1638// Registration
1639services.AddHostedService<CleanupBackgroundService>();
1640```
1641
1642### Queue Processing Service
1643
1644```csharp
1645public class EmailQueueService : BackgroundService
1646{
1647 private readonly Channel<EmailMessage> _channel;
1648 private readonly IServiceScopeFactory _scopeFactory;
1649 private readonly ILogger<EmailQueueService> _logger;
1650
1651 public EmailQueueService(
1652 Channel<EmailMessage> channel,
1653 IServiceScopeFactory scopeFactory,
1654 ILogger<EmailQueueService> logger)
1655 {
1656 _channel = channel;
1657 _scopeFactory = scopeFactory;
1658 _logger = logger;
1659 }
1660
1661 protected override async Task ExecuteAsync(CancellationToken stoppingToken)
1662 {
1663 await foreach (var message in _channel.Reader.ReadAllAsync(stoppingToken))
1664 {
1665 try
1666 {
1667 using var scope = _scopeFactory.CreateScope();
1668 var emailService = scope.ServiceProvider
1669 .GetRequiredService<IEmailService>();
1670
1671 await emailService.SendAsync(message, stoppingToken);
1672
1673 _logger.LogInformation(
1674 "Sent email to {Recipient}",
1675 message.To);
1676 }
1677 catch (Exception ex)
1678 {
1679 _logger.LogError(ex,
1680 "Failed to send email to {Recipient}",
1681 message.To);
1682 }
1683 }
1684 }
1685}
1686
1687// Channel setup
1688services.AddSingleton(Channel.CreateUnbounded<EmailMessage>(
1689 new UnboundedChannelOptions
1690 {
1691 SingleReader = true,
1692 SingleWriter = false
1693 }));
1694
1695services.AddHostedService<EmailQueueService>();
1696
1697// Producer service
1698public class EmailQueueProducer
1699{
1700 private readonly Channel<EmailMessage> _channel;
1701
1702 public EmailQueueProducer(Channel<EmailMessage> channel)
1703 {
1704 _channel = channel;
1705 }
1706
1707 public async Task QueueEmailAsync(EmailMessage message)
1708 {
1709 await _channel.Writer.WriteAsync(message);
1710 }
1711}
1712```
1713
1714### Timed Background Service with Health Check
1715
1716```csharp
1717public class HealthCheckBackgroundService : BackgroundService, IHealthCheck
1718{
1719 private volatile bool _isHealthy = true;
1720 private DateTime _lastSuccessfulRun = DateTime.UtcNow;
1721 private readonly TimeSpan _maxTimeBetweenRuns = TimeSpan.FromMinutes(5);
1722
1723 protected override async Task ExecuteAsync(CancellationToken stoppingToken)
1724 {
1725 while (!stoppingToken.IsCancellationRequested)
1726 {
1727 try
1728 {
1729 await DoWorkAsync(stoppingToken);
1730 _lastSuccessfulRun = DateTime.UtcNow;
1731 _isHealthy = true;
1732 }
1733 catch (Exception)
1734 {
1735 _isHealthy = false;
1736 }
1737
1738 await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
1739 }
1740 }
1741
1742 private Task DoWorkAsync(CancellationToken stoppingToken)
1743 {
1744 // Work implementation
1745 return Task.CompletedTask;
1746 }
1747
1748 public Task<HealthCheckResult> CheckHealthAsync(
1749 HealthCheckContext context,
1750 CancellationToken cancellationToken = default)
1751 {
1752 if (!_isHealthy)
1753 {
1754 return Task.FromResult(HealthCheckResult.Unhealthy(
1755 "Background service is unhealthy"));
1756 }
1757
1758 if (DateTime.UtcNow - _lastSuccessfulRun > _maxTimeBetweenRuns)
1759 {
1760 return Task.FromResult(HealthCheckResult.Degraded(
1761 $"Last successful run was {_lastSuccessfulRun}"));
1762 }
1763
1764 return Task.FromResult(HealthCheckResult.Healthy());
1765 }
1766}
1767
1768// Registration
1769services.AddHostedService<HealthCheckBackgroundService>();
1770services.AddHealthChecks()
1771 .AddCheck<HealthCheckBackgroundService>("background-service");
1772```
1773
1774---
1775
1776## 🧪 Testing
1777
1778### Unit Test Structure (xUnit)
1779
1780```csharp
1781using Xunit;
1782using Moq;
1783using FluentAssertions;
1784
1785namespace MyApp.UnitTests.Services;
1786
1787public class UserServiceTests
1788{
1789 private readonly Mock<IUserRepository> _userRepositoryMock;
1790 private readonly Mock<IEmailService> _emailServiceMock;
1791 private readonly Mock<ILogger<UserService>> _loggerMock;
1792 private readonly UserService _sut; // System Under Test
1793
1794 public UserServiceTests()
1795 {
1796 _userRepositoryMock = new Mock<IUserRepository>();
1797 _emailServiceMock = new Mock<IEmailService>();
1798 _loggerMock = new Mock<ILogger<UserService>>();
1799
1800 _sut = new UserService(
1801 _userRepositoryMock.Object,
1802 _emailServiceMock.Object,
1803 _loggerMock.Object);
1804 }
1805
1806 [Fact]
1807 public async Task GetByIdAsync_WithValidId_ReturnsUser()
1808 {
1809 // Arrange
1810 var userId = Guid.NewGuid();
1811 var expectedUser = new User
1812 {
1813 Id = userId,
1814 Email = "test@example.com",
1815 FirstName = "John",
1816 LastName = "Doe"
1817 };
1818
1819 _userRepositoryMock
1820 .Setup(r => r.GetByIdAsync(userId, It.IsAny<CancellationToken>()))
1821 .ReturnsAsync(expectedUser);
1822
1823 // Act
1824 var result = await _sut.GetByIdAsync(userId);
1825
1826 // Assert
1827 result.Should().NotBeNull();
1828 result!.Id.Should().Be(userId);
1829 result.Email.Should().Be("test@example.com");
1830
1831 _userRepositoryMock.Verify(
1832 r => r.GetByIdAsync(userId, It.IsAny<CancellationToken>()),
1833 Times.Once);
1834 }
1835
1836 [Fact]
1837 public async Task GetByIdAsync_WithInvalidId_ReturnsNull()
1838 {
1839 // Arrange
1840 var userId = Guid.NewGuid();
1841
1842 _userRepositoryMock
1843 .Setup(r => r.GetByIdAsync(userId, It.IsAny<CancellationToken>()))
1844 .ReturnsAsync((User?)null);
1845
1846 // Act
1847 var result = await _sut.GetByIdAsync(userId);
1848
1849 // Assert
1850 result.Should().BeNull();
1851 }
1852
1853 [Theory]
1854 [InlineData("")]
1855 [InlineData(" ")]
1856 [InlineData(null)]
1857 public async Task CreateAsync_WithInvalidEmail_ThrowsValidationException(
1858 string? email)
1859 {
1860 // Arrange
1861 var request = new CreateUserRequest
1862 {
1863 Email = email!,
1864 FirstName = "John",
1865 LastName = "Doe"
1866 };
1867
1868 // Act
1869 var act = () => _sut.CreateAsync(request);
1870
1871 // Assert
1872 await act.Should().ThrowAsync<ValidationException>()
1873 .WithMessage("*email*");
1874 }
1875
1876 [Fact]
1877 public async Task CreateAsync_WithValidRequest_SendsWelcomeEmail()
1878 {
1879 // Arrange
1880 var request = new CreateUserRequest
1881 {
1882 Email = "test@example.com",
1883 FirstName = "John",
1884 LastName = "Doe"
1885 };
1886
1887 _userRepositoryMock
1888 .Setup(r => r.AddAsync(It.IsAny<User>(), It.IsAny<CancellationToken>()))
1889 .ReturnsAsync((User u, CancellationToken _) => u);
1890
1891 // Act
1892 await _sut.CreateAsync(request);
1893
1894 // Assert
1895 _emailServiceMock.Verify(
1896 e => e.SendWelcomeEmailAsync(
1897 request.Email,
1898 It.IsAny<CancellationToken>()),
1899 Times.Once);
1900 }
1901}
1902```
1903
1904### Integration Tests with WebApplicationFactory
1905
1906```csharp
1907using Microsoft.AspNetCore.Mvc.Testing;
1908using Microsoft.EntityFrameworkCore;
1909using Microsoft.Extensions.DependencyInjection;
1910
1911namespace MyApp.IntegrationTests;
1912
1913public class CustomWebApplicationFactory<TProgram>
1914 : WebApplicationFactory<TProgram> where TProgram : class
1915{
1916 protected override void ConfigureWebHost(IWebHostBuilder builder)
1917 {
1918 builder.ConfigureServices(services =>
1919 {
1920 // Remove existing DbContext registration
1921 var descriptor = services.SingleOrDefault(
1922 d => d.ServiceType == typeof(DbContextOptions<AppDbContext>));
1923
1924 if (descriptor != null)
1925 {
1926 services.Remove(descriptor);
1927 }
1928
1929 // Add in-memory database
1930 services.AddDbContext<AppDbContext>(options =>
1931 {
1932 options.UseInMemoryDatabase("TestDb");
1933 });
1934
1935 // Replace external services with mocks
1936 services.AddScoped<IEmailService, FakeEmailService>();
1937
1938 // Build service provider and ensure database is created
1939 var sp = services.BuildServiceProvider();
1940 using var scope = sp.CreateScope();
1941 var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
1942 db.Database.EnsureCreated();
1943
1944 // Seed test data
1945 SeedTestData(db);
1946 });
1947
1948 builder.UseEnvironment("Testing");
1949 }
1950
1951 private static void SeedTestData(AppDbContext context)
1952 {
1953 context.Users.AddRange(
1954 new User
1955 {
1956 Id = Guid.Parse("11111111-1111-1111-1111-111111111111"),
1957 Email = "admin@test.com",
1958 FirstName = "Admin",
1959 LastName = "User"
1960 },
1961 new User
1962 {
1963 Id = Guid.Parse("22222222-2222-2222-2222-222222222222"),
1964 Email = "user@test.com",
1965 FirstName = "Regular",
1966 LastName = "User"
1967 });
1968
1969 context.SaveChanges();
1970 }
1971}
1972
1973public class UsersControllerTests : IClassFixture<CustomWebApplicationFactory<Program>>
1974{
1975 private readonly HttpClient _client;
1976 private readonly CustomWebApplicationFactory<Program> _factory;
1977
1978 public UsersControllerTests(CustomWebApplicationFactory<Program> factory)
1979 {
1980 _factory = factory;
1981 _client = factory.CreateClient(new WebApplicationFactoryClientOptions
1982 {
1983 AllowAutoRedirect = false
1984 });
1985 }
1986
1987 [Fact]
1988 public async Task GetUsers_ReturnsSuccessAndUsers()
1989 {
1990 // Act
1991 var response = await _client.GetAsync("/api/users");
1992
1993 // Assert
1994 response.EnsureSuccessStatusCode();
1995
1996 var users = await response.Content
1997 .ReadFromJsonAsync<IEnumerable<UserDto>>();
1998
1999 users.Should().NotBeNull();
2000 users.Should().HaveCountGreaterThan(0);
2001 }
2002
2003 [Fact]
2004 public async Task GetUserById_WithValidId_ReturnsUser()
2005 {
2006 // Arrange
2007 var userId = "11111111-1111-1111-1111-111111111111";
2008
2009 // Act
2010 var response = await _client.GetAsync($"/api/users/{userId}");
2011
2012 // Assert
2013 response.EnsureSuccessStatusCode();
2014
2015 var user = await response.Content.ReadFromJsonAsync<UserDto>();
2016
2017 user.Should().NotBeNull();
2018 user!.Email.Should().Be("admin@test.com");
2019 }
2020
2021 [Fact]
2022 public async Task GetUserById_WithInvalidId_ReturnsNotFound()
2023 {
2024 // Arrange
2025 var userId = Guid.NewGuid();
2026
2027 // Act
2028 var response = await _client.GetAsync($"/api/users/{userId}");
2029
2030 // Assert
2031 response.StatusCode.Should().Be(HttpStatusCode.NotFound);
2032 }
2033
2034 [Fact]
2035 public async Task CreateUser_WithValidData_ReturnsCreated()
2036 {
2037 // Arrange
2038 var request = new CreateUserRequest
2039 {
2040 Email = "new@test.com",
2041 FirstName = "New",
2042 LastName = "User"
2043 };
2044
2045 // Act
2046 var response = await _client.PostAsJsonAsync("/api/users", request);
2047
2048 // Assert
2049 response.StatusCode.Should().Be(HttpStatusCode.Created);
2050
2051 var user = await response.Content.ReadFromJsonAsync<UserDto>();
2052
2053 user.Should().NotBeNull();
2054 user!.Email.Should().Be("new@test.com");
2055
2056 response.Headers.Location.Should().NotBeNull();
2057 }
2058
2059 [Fact]
2060 public async Task CreateUser_WithInvalidData_ReturnsBadRequest()
2061 {
2062 // Arrange
2063 var request = new CreateUserRequest
2064 {
2065 Email = "invalid-email",
2066 FirstName = "",
2067 LastName = ""
2068 };
2069
2070 // Act
2071 var response = await _client.PostAsJsonAsync("/api/users", request);
2072
2073 // Assert
2074 response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
2075 }
2076}
2077```
2078
2079### Test with Authentication
2080
2081```csharp
2082public class AuthenticatedTestsBase : IClassFixture<CustomWebApplicationFactory<Program>>
2083{
2084 protected readonly HttpClient _client;
2085 protected readonly CustomWebApplicationFactory<Program> _factory;
2086
2087 public AuthenticatedTestsBase(CustomWebApplicationFactory<Program> factory)
2088 {
2089 _factory = factory;
2090 _client = factory.CreateClient();
2091 }
2092
2093 protected void AuthenticateAs(string role = "User")
2094 {
2095 var token = GenerateTestToken(role);
2096 _client.DefaultRequestHeaders.Authorization =
2097 new AuthenticationHeaderValue("Bearer", token);
2098 }
2099
2100 private string GenerateTestToken(string role)
2101 {
2102 var claims = new[]
2103 {
2104 new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()),
2105 new Claim(ClaimTypes.Email, "test@example.com"),
2106 new Claim(ClaimTypes.Role, role)
2107 };
2108
2109 var key = new SymmetricSecurityKey(
2110 Encoding.UTF8.GetBytes("test-secret-key-at-least-32-characters"));
2111 var credentials = new SigningCredentials(
2112 key, SecurityAlgorithms.HmacSha256);
2113
2114 var token = new JwtSecurityToken(
2115 issuer: "test-issuer",
2116 audience: "test-audience",
2117 claims: claims,
2118 expires: DateTime.UtcNow.AddHours(1),
2119 signingCredentials: credentials);
2120
2121 return new JwtSecurityTokenHandler().WriteToken(token);
2122 }
2123}
2124
2125public class ProtectedEndpointTests : AuthenticatedTestsBase
2126{
2127 public ProtectedEndpointTests(CustomWebApplicationFactory<Program> factory)
2128 : base(factory)
2129 {
2130 }
2131
2132 [Fact]
2133 public async Task AdminEndpoint_WithoutAuth_ReturnsUnauthorized()
2134 {
2135 // Act
2136 var response = await _client.GetAsync("/api/admin/dashboard");
2137
2138 // Assert
2139 response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
2140 }
2141
2142 [Fact]
2143 public async Task AdminEndpoint_WithUserRole_ReturnsForbidden()
2144 {
2145 // Arrange
2146 AuthenticateAs("User");
2147
2148 // Act
2149 var response = await _client.GetAsync("/api/admin/dashboard");
2150
2151 // Assert
2152 response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
2153 }
2154
2155 [Fact]
2156 public async Task AdminEndpoint_WithAdminRole_ReturnsSuccess()
2157 {
2158 // Arrange
2159 AuthenticateAs("Admin");
2160
2161 // Act
2162 var response = await _client.GetAsync("/api/admin/dashboard");
2163
2164 // Assert
2165 response.EnsureSuccessStatusCode();
2166 }
2167}
2168```
2169
2170### NUnit Alternative
2171
2172```csharp
2173using NUnit.Framework;
2174using Moq;
2175using FluentAssertions;
2176
2177namespace MyApp.UnitTests.Services;
2178
2179[TestFixture]
2180public class UserServiceNUnitTests
2181{
2182 private Mock<IUserRepository> _userRepositoryMock = null!;
2183 private Mock<IEmailService> _emailServiceMock = null!;
2184 private UserService _sut = null!;
2185
2186 [SetUp]
2187 public void Setup()
2188 {
2189 _userRepositoryMock = new Mock<IUserRepository>();
2190 _emailServiceMock = new Mock<IEmailService>();
2191
2192 _sut = new UserService(
2193 _userRepositoryMock.Object,
2194 _emailServiceMock.Object);
2195 }
2196
2197 [Test]
2198 public async Task GetByIdAsync_WithValidId_ReturnsUser()
2199 {
2200 // Arrange
2201 var userId = Guid.NewGuid();
2202 var expectedUser = new User { Id = userId, Email = "test@example.com" };
2203
2204 _userRepositoryMock
2205 .Setup(r => r.GetByIdAsync(userId, It.IsAny<CancellationToken>()))
2206 .ReturnsAsync(expectedUser);
2207
2208 // Act
2209 var result = await _sut.GetByIdAsync(userId);
2210
2211 // Assert
2212 result.Should().NotBeNull();
2213 result!.Id.Should().Be(userId);
2214 }
2215
2216 [TestCase("")]
2217 [TestCase(" ")]
2218 [TestCase(null)]
2219 public async Task CreateAsync_WithInvalidEmail_ThrowsException(string? email)
2220 {
2221 // Arrange
2222 var request = new CreateUserRequest { Email = email! };
2223
2224 // Act & Assert
2225 await _sut.Invoking(s => s.CreateAsync(request))
2226 .Should().ThrowAsync<ValidationException>();
2227 }
2228
2229 [Test]
2230 [TestCaseSource(nameof(GetTestUsers))]
2231 public async Task GetByIdAsync_ReturnsExpectedUser(Guid id, string email)
2232 {
2233 // Arrange
2234 _userRepositoryMock
2235 .Setup(r => r.GetByIdAsync(id, It.IsAny<CancellationToken>()))
2236 .ReturnsAsync(new User { Id = id, Email = email });
2237
2238 // Act
2239 var result = await _sut.GetByIdAsync(id);
2240
2241 // Assert
2242 result!.Email.Should().Be(email);
2243 }
2244
2245 private static IEnumerable<TestCaseData> GetTestUsers()
2246 {
2247 yield return new TestCaseData(
2248 Guid.Parse("11111111-1111-1111-1111-111111111111"),
2249 "user1@test.com");
2250 yield return new TestCaseData(
2251 Guid.Parse("22222222-2222-2222-2222-222222222222"),
2252 "user2@test.com");
2253 }
2254}
2255```
2256
2257---
2258
2259## 🔄 Common Patterns
2260
2261### Result Pattern
2262
2263```csharp
2264public class Result<T>
2265{
2266 public bool IsSuccess { get; }
2267 public T? Value { get; }
2268 public string? Error { get; }
2269 public IReadOnlyList<string> Errors { get; }
2270
2271 private Result(bool isSuccess, T? value, string? error, IEnumerable<string>? errors)
2272 {
2273 IsSuccess = isSuccess;
2274 Value = value;
2275 Error = error;
2276 Errors = errors?.ToList() ?? [];
2277 }
2278
2279 public static Result<T> Success(T value) =>
2280 new(true, value, null, null);
2281
2282 public static Result<T> Failure(string error) =>
2283 new(false, default, error, [error]);
2284
2285 public static Result<T> Failure(IEnumerable<string> errors) =>
2286 new(false, default, errors.FirstOrDefault(), errors);
2287
2288 public TResult Match<TResult>(
2289 Func<T, TResult> onSuccess,
2290 Func<IReadOnlyList<string>, TResult> onFailure)
2291 {
2292 return IsSuccess ? onSuccess(Value!) : onFailure(Errors);
2293 }
2294}
2295
2296// Usage
2297public async Task<Result<UserDto>> CreateUserAsync(CreateUserRequest request)
2298{
2299 var validationResult = await _validator.ValidateAsync(request);
2300
2301 if (!validationResult.IsValid)
2302 {
2303 return Result<UserDto>.Failure(
2304 validationResult.Errors.Select(e => e.ErrorMessage));
2305 }
2306
2307 var existingUser = await _repository.GetByEmailAsync(request.Email);
2308
2309 if (existingUser is not null)
2310 {
2311 return Result<UserDto>.Failure("Email already exists");
2312 }
2313
2314 var user = new User
2315 {
2316 Email = request.Email,
2317 FirstName = request.FirstName,
2318 LastName = request.LastName
2319 };
2320
2321 await _repository.AddAsync(user);
2322
2323 return Result<UserDto>.Success(user.ToDto());
2324}
2325
2326// Controller usage
2327[HttpPost]
2328public async Task<IActionResult> CreateUser(CreateUserRequest request)
2329{
2330 var result = await _userService.CreateUserAsync(request);
2331
2332 return result.Match<IActionResult>(
2333 onSuccess: user => CreatedAtAction(nameof(GetUser), new { id = user.Id }, user),
2334 onFailure: errors => BadRequest(new { Errors = errors }));
2335}
2336```
2337
2338### CQRS Pattern
2339
2340```csharp
2341// Command
2342public record CreateUserCommand(
2343 string Email,
2344 string FirstName,
2345 string LastName) : IRequest<Result<Guid>>;
2346
2347// Command Handler
2348public class CreateUserCommandHandler : IRequestHandler<CreateUserCommand, Result<Guid>>
2349{
2350 private readonly IUserRepository _repository;
2351 private readonly IValidator<CreateUserCommand> _validator;
2352
2353 public CreateUserCommandHandler(
2354 IUserRepository repository,
2355 IValidator<CreateUserCommand> validator)
2356 {
2357 _repository = repository;
2358 _validator = validator;
2359 }
2360
2361 public async Task<Result<Guid>> Handle(
2362 CreateUserCommand request,
2363 CancellationToken cancellationToken)
2364 {
2365 var validationResult = await _validator.ValidateAsync(
2366 request, cancellationToken);
2367
2368 if (!validationResult.IsValid)
2369 {
2370 return Result<Guid>.Failure(
2371 validationResult.Errors.Select(e => e.ErrorMessage));
2372 }
2373
2374 var user = new User
2375 {
2376 Email = request.Email,
2377 FirstName = request.FirstName,
2378 LastName = request.LastName
2379 };
2380
2381 await _repository.AddAsync(user, cancellationToken);
2382
2383 return Result<Guid>.Success(user.Id);
2384 }
2385}
2386
2387// Query
2388public record GetUserByIdQuery(Guid Id) : IRequest<UserDto?>;
2389
2390// Query Handler
2391public class GetUserByIdQueryHandler : IRequestHandler<GetUserByIdQuery, UserDto?>
2392{
2393 private readonly IUserRepository _repository;
2394
2395 public GetUserByIdQueryHandler(IUserRepository repository)
2396 {
2397 _repository = repository;
2398 }
2399
2400 public async Task<UserDto?> Handle(
2401 GetUserByIdQuery request,
2402 CancellationToken cancellationToken)
2403 {
2404 var user = await _repository.GetByIdAsync(request.Id, cancellationToken);
2405 return user?.ToDto();
2406 }
2407}
2408
2409// Controller
2410[ApiController]
2411[Route("api/[controller]")]
2412public class UsersController : ControllerBase
2413{
2414 private readonly IMediator _mediator;
2415
2416 public UsersController(IMediator mediator)
2417 {
2418 _mediator = mediator;
2419 }
2420
2421 [HttpGet("{id:guid}")]
2422 public async Task<ActionResult<UserDto>> GetUser(Guid id)
2423 {
2424 var user = await _mediator.Send(new GetUserByIdQuery(id));
2425 return user is null ? NotFound() : Ok(user);
2426 }
2427
2428 [HttpPost]
2429 public async Task<IActionResult> CreateUser(CreateUserCommand command)
2430 {
2431 var result = await _mediator.Send(command);
2432
2433 return result.Match<IActionResult>(
2434 onSuccess: id => CreatedAtAction(nameof(GetUser), new { id }, null),
2435 onFailure: errors => BadRequest(new { Errors = errors }));
2436 }
2437}
2438```
2439
2440### Unit of Work Pattern
2441
2442```csharp
2443public interface IUnitOfWork : IDisposable
2444{
2445 IUserRepository Users { get; }
2446 IOrderRepository Orders { get; }
2447 IProductRepository Products { get; }
2448 Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
2449 Task BeginTransactionAsync(CancellationToken cancellationToken = default);
2450 Task CommitTransactionAsync(CancellationToken cancellationToken = default);
2451 Task RollbackTransactionAsync(CancellationToken cancellationToken = default);
2452}
2453
2454public class UnitOfWork : IUnitOfWork
2455{
2456 private readonly AppDbContext _context;
2457 private IDbContextTransaction? _transaction;
2458
2459 public UnitOfWork(
2460 AppDbContext context,
2461 IUserRepository users,
2462 IOrderRepository orders,
2463 IProductRepository products)
2464 {
2465 _context = context;
2466 Users = users;
2467 Orders = orders;
2468 Products = products;
2469 }
2470
2471 public IUserRepository Users { get; }
2472 public IOrderRepository Orders { get; }
2473 public IProductRepository Products { get; }
2474
2475 public async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
2476 {
2477 return await _context.SaveChangesAsync(cancellationToken);
2478 }
2479
2480 public async Task BeginTransactionAsync(CancellationToken cancellationToken = default)
2481 {
2482 _transaction = await _context.Database
2483 .BeginTransactionAsync(cancellationToken);
2484 }
2485
2486 public async Task CommitTransactionAsync(CancellationToken cancellationToken = default)
2487 {
2488 if (_transaction is not null)
2489 {
2490 await _transaction.CommitAsync(cancellationToken);
2491 await _transaction.DisposeAsync();
2492 _transaction = null;
2493 }
2494 }
2495
2496 public async Task RollbackTransactionAsync(CancellationToken cancellationToken = default)
2497 {
2498 if (_transaction is not null)
2499 {
2500 await _transaction.RollbackAsync(cancellationToken);
2501 await _transaction.DisposeAsync();
2502 _transaction = null;
2503 }
2504 }
2505
2506 public void Dispose()
2507 {
2508 _transaction?.Dispose();
2509 _context.Dispose();
2510 }
2511}
2512
2513// Usage
2514public class OrderService : IOrderService
2515{
2516 private readonly IUnitOfWork _unitOfWork;
2517
2518 public OrderService(IUnitOfWork unitOfWork)
2519 {
2520 _unitOfWork = unitOfWork;
2521 }
2522
2523 public async Task<Order> CreateOrderAsync(CreateOrderRequest request)
2524 {
2525 await _unitOfWork.BeginTransactionAsync();
2526
2527 try
2528 {
2529 var user = await _unitOfWork.Users.GetByIdAsync(request.UserId);
2530
2531 if (user is null)
2532 {
2533 throw new NotFoundException("User not found");
2534 }
2535
2536 var order = new Order
2537 {
2538 UserId = user.Id,
2539 OrderDate = DateTime.UtcNow,
2540 Items = request.Items.Select(i => new OrderItem
2541 {
2542 ProductId = i.ProductId,
2543 Quantity = i.Quantity,
2544 Price = i.Price
2545 }).ToList()
2546 };
2547
2548 await _unitOfWork.Orders.AddAsync(order);
2549
2550 // Update product stock
2551 foreach (var item in request.Items)
2552 {
2553 var product = await _unitOfWork.Products.GetByIdAsync(item.ProductId);
2554 product!.Stock -= item.Quantity;
2555 await _unitOfWork.Products.UpdateAsync(product);
2556 }
2557
2558 await _unitOfWork.SaveChangesAsync();
2559 await _unitOfWork.CommitTransactionAsync();
2560
2561 return order;
2562 }
2563 catch
2564 {
2565 await _unitOfWork.RollbackTransactionAsync();
2566 throw;
2567 }
2568 }
2569}
2570```
2571
2572---
2573
2574## ✅ Best Practices
2575
2576### Code Organization
2577
2578| Practice | Description |
2579| ------------------ | --------------------------------------------------------- |
2580| Clean Architecture | Separate concerns into layers (Core, Infrastructure, API) |
2581| Vertical Slices | Organize by feature for complex applications |
2582| SOLID Principles | Single responsibility, dependency injection, etc. |
2583| DTOs | Never expose entities directly to API responses |
2584
2585### Performance
2586
2587| Practice | Description |
2588| ------------------------- | ------------------------------------- |
2589| Async/Await | Use async for I/O operations |
2590| CancellationToken | Pass through all async chains |
2591| IQueryable vs IEnumerable | Filter at database level |
2592| Compiled Queries | For frequently executed queries |
2593| Caching | Use IMemoryCache or IDistributedCache |
2594
2595### Security
2596
2597| Practice | Description |
2598| --------------------- | ----------------------------------- |
2599| Input Validation | Validate all user input |
2600| Parameterized Queries | Prevent SQL injection |
2601| HTTPS | Always use HTTPS in production |
2602| Secrets Management | Use User Secrets/Key Vault |
2603| CORS | Configure properly for your domains |
2604
2605### Error Handling
2606
2607```csharp
2608// Custom exception types
2609public class NotFoundException : Exception
2610{
2611 public NotFoundException(string message) : base(message) { }
2612 public NotFoundException(string name, object key)
2613 : base($"Entity \"{name}\" ({key}) was not found.") { }
2614}
2615
2616public class ValidationException : Exception
2617{
2618 public IReadOnlyList<string> Errors { get; }
2619
2620 public ValidationException(IEnumerable<string> errors)
2621 : base("One or more validation errors occurred.")
2622 {
2623 Errors = errors.ToList();
2624 }
2625}
2626
2627public class ForbiddenException : Exception
2628{
2629 public ForbiddenException(string message = "Access denied")
2630 : base(message) { }
2631}
2632```
2633
2634### Logging Best Practices
2635
2636```csharp
2637// Structured logging with semantic values
2638_logger.LogInformation(
2639 "User {UserId} created order {OrderId} for {Amount:C}",
2640 userId, orderId, amount);
2641
2642// Log levels
2643_logger.LogTrace("Detailed debugging info");
2644_logger.LogDebug("Debugging info");
2645_logger.LogInformation("General info");
2646_logger.LogWarning("Something unexpected but not an error");
2647_logger.LogError(ex, "An error occurred");
2648_logger.LogCritical(ex, "A critical failure");
2649
2650// Scopes for correlation
2651using (_logger.BeginScope(new Dictionary<string, object>
2652{
2653 ["UserId"] = userId,
2654 ["OrderId"] = orderId
2655}))
2656{
2657 _logger.LogInformation("Processing order");
2658 // All logs within scope include UserId and OrderId
2659}
2660```
2661
2662### Health Checks
2663
2664```csharp
2665services.AddHealthChecks()
2666 .AddDbContextCheck<AppDbContext>("database")
2667 .AddRedis(connectionString, "redis")
2668 .AddUrlGroup(new Uri("https://api.example.com/health"), "external-api")
2669 .AddCheck<CustomHealthCheck>("custom");
2670
2671app.MapHealthChecks("/health", new HealthCheckOptions
2672{
2673 ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
2674});
2675
2676app.MapHealthChecks("/health/ready", new HealthCheckOptions
2677{
2678 Predicate = check => check.Tags.Contains("ready")
2679});
2680
2681app.MapHealthChecks("/health/live", new HealthCheckOptions
2682{
2683 Predicate = _ => false // Just returns healthy if app is running
2684});
2685```
2686
2687---
2688
2689## 📚 Additional Resources
2690
2691- [.NET Documentation](https://docs.microsoft.com/dotnet/)
2692- [ASP.NET Core Documentation](https://docs.microsoft.com/aspnet/core/)
2693- [EF Core Documentation](https://docs.microsoft.com/ef/core/)
2694- [C# Language Reference](https://docs.microsoft.com/dotnet/csharp/)
2695- [.NET Architecture Guides](https://dotnet.microsoft.com/learn/aspnet/architecture)
2696
2697---
2698
2699> **Note**: This skill covers .NET 8+ patterns and best practices. For earlier versions, some features may not be available.