first commit

This commit is contained in:
2026-02-26 14:04:18 +07:00
parent 57ac80a666
commit 4b7236493f
92 changed files with 4999 additions and 0 deletions

View File

@@ -0,0 +1,16 @@
using MediatR;
using Microsoft.AspNetCore.Mvc;
namespace MyNewProjectName.AdminAPI.Controllers;
/// <summary>
/// Base API controller with common functionality
/// </summary>
[ApiController]
[Route("api/admin/[controller]")]
public abstract class BaseApiController : ControllerBase
{
private ISender? _mediator;
protected ISender Mediator => _mediator ??= HttpContext.RequestServices.GetRequiredService<ISender>();
}

View File

@@ -0,0 +1,36 @@
using Serilog.Context;
namespace MyNewProjectName.AdminAPI.Middleware;
/// <summary>
/// Middleware to generate and track correlation ID for each request
/// This ID is added to HTTP headers and Serilog log context for easy tracing
/// </summary>
public class CorrelationIdMiddleware
{
private readonly RequestDelegate _next;
private const string CorrelationIdHeaderName = "X-Correlation-ID";
private const string CorrelationIdLogPropertyName = "CorrelationId";
public CorrelationIdMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
// Get correlation ID from request header, or generate a new one
var correlationId = context.Request.Headers[CorrelationIdHeaderName].FirstOrDefault()
?? $"req-{Guid.NewGuid():N}";
// Add correlation ID to response header
context.Response.Headers[CorrelationIdHeaderName] = correlationId;
// Add correlation ID to Serilog log context
// All logs within this request will automatically include this correlation ID
using (LogContext.PushProperty(CorrelationIdLogPropertyName, correlationId))
{
await _next(context);
}
}
}

View File

@@ -0,0 +1,114 @@
using System.Net;
using System.Text.Json;
using MyNewProjectName.Contracts.DTOs.Responses;
using MyNewProjectName.Domain.Exceptions;
using Serilog;
namespace MyNewProjectName.AdminAPI.Middleware;
/// <summary>
/// Global exception handling middleware
/// Catches all unhandled exceptions, logs them to Serilog with full details,
/// and returns a standardized error response without exposing stack traces
/// </summary>
public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly Serilog.ILogger _logger;
public ExceptionHandlingMiddleware(RequestDelegate next, Serilog.ILogger 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)
{
// Get correlation ID from header (set by CorrelationIdMiddleware)
var correlationId = context.Request.Headers["X-Correlation-ID"].FirstOrDefault() ?? "unknown";
// Log full exception details to Serilog (including stack trace)
// This will be searchable by CorrelationId
_logger.Error(
exception,
"Unhandled exception occurred. CorrelationId: {CorrelationId}, Path: {Path}, Method: {Method}",
correlationId,
context.Request.Path,
context.Request.Method
);
// Safety check: If response has already started, we cannot modify headers/status code
// This prevents InvalidOperationException: "Headers are read-only, response has already started"
if (context.Response.HasStarted)
{
_logger.Warning(
"Response has already started. Cannot modify HTTP status code or headers. CorrelationId: {CorrelationId}",
correlationId
);
return;
}
var response = context.Response;
// Clear any existing response data
response.Clear();
response.ContentType = "application/json";
// Determine status code and user-friendly message
var (statusCode, message, errors) = exception switch
{
ValidationException validationEx => (
HttpStatusCode.BadRequest,
"Validation failed",
validationEx.Errors.SelectMany(e => e.Value).ToList()),
NotFoundException => (
HttpStatusCode.NotFound,
exception.Message,
new List<string>()),
DomainException => (
HttpStatusCode.BadRequest,
exception.Message,
new List<string>()),
UnauthorizedAccessException => (
HttpStatusCode.Unauthorized,
"Unauthorized",
new List<string>()),
_ => (
HttpStatusCode.InternalServerError,
"An error occurred while processing your request",
new List<string>())
};
response.StatusCode = (int)statusCode;
// Return standardized error response (NO stack trace exposed to client)
var result = JsonSerializer.Serialize(new ApiResponse
{
Success = false,
Message = message,
Errors = errors.Any() ? errors : null
}, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
await response.WriteAsync(result);
}
}

View File

@@ -0,0 +1,133 @@
using System.Diagnostics;
using System.Text;
using Microsoft.Extensions.Configuration;
using Serilog;
namespace MyNewProjectName.AdminAPI.Middleware;
/// <summary>
/// Middleware to log request and response bodies
/// WARNING: This can generate large log files. Use with caution in production.
/// Consider enabling only for specific environments or endpoints.
/// </summary>
public class RequestResponseLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly Serilog.ILogger _logger;
private readonly bool _enableRequestLogging;
private readonly bool _enableResponseLogging;
// Paths that should NOT be logged (e.g., health checks, metrics)
private static readonly string[] ExcludedPaths = new[]
{
"/health",
"/metrics",
"/favicon.ico"
};
public RequestResponseLoggingMiddleware(
RequestDelegate next,
Serilog.ILogger logger,
IConfiguration configuration)
{
_next = next;
_logger = logger;
_enableRequestLogging = configuration.GetValue<bool>("Logging:EnableRequestLogging", false);
_enableResponseLogging = configuration.GetValue<bool>("Logging:EnableResponseLogging", false);
}
public async Task InvokeAsync(HttpContext context)
{
// Skip logging for excluded paths
if (ExcludedPaths.Any(path => context.Request.Path.StartsWithSegments(path)))
{
await _next(context);
return;
}
var stopwatch = Stopwatch.StartNew();
var requestBody = string.Empty;
var responseBody = string.Empty;
// Log request
if (_enableRequestLogging)
{
requestBody = await ReadRequestBodyAsync(context.Request);
_logger.Information(
"Request: {Method} {Path} {QueryString} | Body: {RequestBody}",
context.Request.Method,
context.Request.Path,
context.Request.QueryString,
requestBody
);
}
// Capture response body
var originalBodyStream = context.Response.Body;
using var responseBodyStream = new MemoryStream();
context.Response.Body = responseBodyStream;
try
{
await _next(context);
}
finally
{
stopwatch.Stop();
// Log response
if (_enableResponseLogging)
{
responseBody = await ReadResponseBodyAsync(context.Response);
await responseBodyStream.CopyToAsync(originalBodyStream);
_logger.Information(
"Response: {StatusCode} | Duration: {Duration}ms | Body: {ResponseBody}",
context.Response.StatusCode,
stopwatch.ElapsedMilliseconds,
responseBody
);
}
else
{
await responseBodyStream.CopyToAsync(originalBodyStream);
}
context.Response.Body = originalBodyStream;
}
}
private static async Task<string> ReadRequestBodyAsync(HttpRequest request)
{
// Enable buffering to allow reading the body multiple times
request.EnableBuffering();
using var reader = new StreamReader(
request.Body,
encoding: Encoding.UTF8,
detectEncodingFromByteOrderMarks: false,
leaveOpen: true);
var body = await reader.ReadToEndAsync();
request.Body.Position = 0; // Reset position for next middleware
// Truncate very long bodies to avoid huge logs
return body.Length > 10000 ? body[..10000] + "... (truncated)" : body;
}
private static async Task<string> ReadResponseBodyAsync(HttpResponse response)
{
response.Body.Seek(0, SeekOrigin.Begin);
using var reader = new StreamReader(
response.Body,
encoding: Encoding.UTF8,
detectEncodingFromByteOrderMarks: false,
leaveOpen: true);
var body = await reader.ReadToEndAsync();
response.Body.Seek(0, SeekOrigin.Begin); // Reset position
// Truncate very long bodies to avoid huge logs
return body.Length > 10000 ? body[..10000] + "... (truncated)" : body;
}
}

View File

@@ -0,0 +1,33 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.2.0" />
<!-- Serilog for structured logging -->
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.Seq" Version="8.0.0" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="3.0.1" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="4.0.0" />
<!-- OpenTelemetry for distributed tracing -->
<PackageReference Include="OpenTelemetry.Exporter.Console" Version="1.11.1" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.11.1" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.11.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.11.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.11.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.EntityFrameworkCore" Version="1.0.0-beta.7" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MyNewProjectName.Infrastructure\MyNewProjectName.Infrastructure.csproj" />
<ProjectReference Include="..\MyNewProjectName.Application\MyNewProjectName.Application.csproj" />
<ProjectReference Include="..\MyNewProjectName.Contracts\MyNewProjectName.Contracts.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,6 @@
@MyNewProjectName.AdminAPI_HostAddress = http://localhost:5011
GET {{MyNewProjectName.AdminAPI_HostAddress}}/weatherforecast/
Accept: application/json
###

View File

@@ -0,0 +1,76 @@
using Microsoft.Extensions.Hosting;
using MyNewProjectName.Application;
using MyNewProjectName.Infrastructure;
using MyNewProjectName.Infrastructure.Extensions;
using MyNewProjectName.AdminAPI.Middleware;
using Serilog;
// Create host builder with Serilog
var builder = WebApplication.CreateBuilder(args);
// Configure Serilog
builder.Host.UseSerilogLogging(builder.Configuration);
// Add OpenTelemetry distributed tracing
builder.Services.AddOpenTelemetryTracing("MyNewProjectName.AdminAPI");
// Add services to the container.
builder.Services.AddControllers();
// Add Application Layer
builder.Services.AddApplication();
// Add Infrastructure Layer
builder.Services.AddInfrastructure(builder.Configuration);
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
// Add Swagger
builder.Services.AddEndpointsApiExplorer();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
// Middleware pipeline order is critical:
// 1. CorrelationIdMiddleware - Must be first to track all requests
app.UseMiddleware<CorrelationIdMiddleware>();
// 2. RequestResponseLoggingMiddleware - Optional, enable only when needed
// WARNING: This can generate large log files. Enable only for specific environments.
// For AdminAPI, you might want to enable this more often for audit purposes.
// Configure in appsettings.json: "Logging:EnableRequestLogging" and "Logging:EnableResponseLogging"
app.UseMiddleware<RequestResponseLoggingMiddleware>();
app.UseHttpsRedirection();
// 3. Authentication (built-in)
app.UseAuthentication();
// 4. Authorization (built-in)
app.UseAuthorization();
// 6. ExceptionHandlingMiddleware - Must be last to catch all exceptions
app.UseMiddleware<ExceptionHandlingMiddleware>();
app.MapControllers();
try
{
Log.Information("Starting MyNewProjectName.AdminAPI");
app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application terminated unexpectedly");
throw;
}
finally
{
Log.CloseAndFlush();
}

View File

@@ -0,0 +1,23 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "http://localhost:5011",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "https://localhost:7298;http://localhost:5011",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@@ -0,0 +1,43 @@
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=MyNewProjectNameDb;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True"
},
"Jwt": {
"SecretKey": "YourSuperSecretKeyThatIsAtLeast32CharactersLong!",
"Issuer": "MyNewProjectName",
"Audience": "MyNewProjectName",
"ExpirationInMinutes": 60,
"RefreshTokenExpirationInDays": 7
},
"Redis": {
"ConnectionString": "localhost:6379",
"InstanceName": "MyNewProjectName:",
"DefaultExpirationInMinutes": 30
},
"Serilog": {
"MinimumLevel": "Information",
"Override": {
"Microsoft": "Warning",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore": "Warning",
"System": "Warning"
},
"WriteToConsole": true,
"WriteToFile": true,
"FilePath": "logs/log-.txt",
"RollingInterval": "Day",
"RetainedFileCountLimit": 31,
"SeqUrl": null,
"ElasticsearchUrl": null
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore": "Warning"
},
"EnableRequestLogging": false,
"EnableResponseLogging": false
},
"AllowedHosts": "*"
}