YouBIM.Common.Middlewares.Lib
10.0.0
dotnet add package YouBIM.Common.Middlewares.Lib --version 10.0.0
NuGet\Install-Package YouBIM.Common.Middlewares.Lib -Version 10.0.0
<PackageReference Include="YouBIM.Common.Middlewares.Lib" Version="10.0.0" />
<PackageVersion Include="YouBIM.Common.Middlewares.Lib" Version="10.0.0" />
<PackageReference Include="YouBIM.Common.Middlewares.Lib" />
paket add YouBIM.Common.Middlewares.Lib --version 10.0.0
#r "nuget: YouBIM.Common.Middlewares.Lib, 10.0.0"
#:package YouBIM.Common.Middlewares.Lib@10.0.0
#addin nuget:?package=YouBIM.Common.Middlewares.Lib&version=10.0.0
#tool nuget:?package=YouBIM.Common.Middlewares.Lib&version=10.0.0
YouBIM.Common.Middlewares.Lib
Shared ASP.NET Core middleware and configuration helpers library for YouBIM APIs. It centralizes structured request/response logging, HTTP error handling, and typed reads of common appsettings.json fragments.
Requirements
- .NET 8 (
TargetFramework:net8.0). - Main dependencies:
Microsoft.AspNetCore.App(framework reference),Microsoft.Extensions.Configuration/Binder/Json/Hosting/Logging8.0.x,Newtonsoft.Json13.0.3,Serilog.AspNetCore8.0.0.
Repository layout
| Project | Role |
|---|---|
YouBIM.Common.Middlewares.Lib |
Publishable library: middlewares, extensions, and AppSetting. |
YouBIM.Common.Middlewares.UnitTests |
Tests using MSTest + FluentAssertions + Microsoft.AspNetCore.TestServer. |
YouBIM.Common.Middlewares.Lib.sln |
Solution that includes both projects. |
Architecture by area
1. Logging (YouBIM.Common.Middlewares.Lib.Logging)
Goal: trace each request/response with a fixed, correlatable format using TraceId.
LoggingMiddleware- Enables request body buffering, intercepts the response body with a
MemoryStream, and copies it back to the original stream when done. - Adds the
TraceIdresponse header fromHttpContext. - Request: always logged (via
GetStringRequest+LogInformation). - Response:
- Status codes 100–399:
LogInformation. - 4xx:
LogWarning; log text includes the response body for client errors. - 5xx:
LogError; includes the response body in the log.
- Status codes 100–399:
- Enables request body buffering, intercepts the response body with a
HttpContextExtensions
Formats log lines with templates:TYPE=Request:TRACEID,METHOD,SVC(endpoint display name or path).TYPE=Response:TRACEID,STATUS_CODE,RESPONSE(empty on success unless the middleware fills the body for errors).TYPE=Error: same context as the request plus the error text.
ILoggingMiddleware
MinimalInvoke(HttpContext)contract aligned with the ASP.NET Core middleware pattern.
2. Exceptions (YouBIM.Common.Middlewares.Lib.Exception)
Goal: uniform JSON responses and failure logging with HTTP context.
ResponseError
Serializable DTO:Message,TraceId.BusinessException
Domain/business exception. The dedicated middleware maps it to HTTP 412 Precondition Failed and exposes onlyMessagein JSON (not the full stack as for generic errors).ExceptionHandlerMiddleware(static, extensions)- Extension method
UseCustomErrors(this IApplicationBuilder app, IHostEnvironment environment). - Development: JSON includes full exception detail (
ex.ToString()). - Non-Development: only
ex.Message. - Intended for use with the standard pipeline’s
UseExceptionHandler: the handler readsIExceptionHandlerFeature, logs withGetStringError, and writesResponseErroras JSON withSystem.Text.Json.
- Extension method
CustomExceptionHandlerMiddleware
Middleware that wraps the pipeline intry/catch, logs the error, and returns JSON based on exception type (412 vs 500). Complements or replaces scenarios where the built-in exception handler alone is not enough.
3. Startup configuration (YouBIM.Common.Middlewares.Lib.StartupSettings)
Goal: read typed, repeatable values that commonly appear in appsettings.json across services.
IAppSetting/AppSetting- If the constructor receives a non-null
IConfigurationBuilder, it usesBuild()and ignores theappSettingsFilePathargument on methods (useful in tests withAddJsonStreamor in-memory configuration). - If
_builderisnull, configuration is built withConfigurationBuilder.AddJsonFile(appSettingsFilePath). - Methods bind sections by CLR type name (
typeof(T).Name), so JSON section keys must match:AuthenticateScheme,Security,ConnectionStrings.
- If the constructor receives a non-null
Models under
StartupSettings.SettingsAuthenticateScheme:Active(string collection);GetAuthenticateProviderKeyreturns the first active entry.Security→JWT:IssuerforGetIssuer.ConnectionStrings→DBConnection:ConnectionStringforGetDbConnectionString.
Expected appsettings.json shape (minimal example)
{
"AuthenticateScheme": {
"Active": [ "YouBIM" ]
},
"Security": {
"JWT": {
"Issuer": "https://api.example.com"
}
},
"ConnectionStrings": {
"DBConnection": {
"ConnectionString": "server=...;database=...;"
}
}
}
JSON property names follow the usual ConfigurationBinder conventions (including typical casing variations).
Typical pipeline integration
Suggested order (illustrative; adjust for authentication and other middleware):
UseExceptionHandler+UseCustomErrors(env)for errors not caught in controllers.- Optional:
UseMiddleware<CustomExceptionHandlerMiddleware>if you need an explicit try/catch wrapper. UseMiddleware<LoggingMiddleware>for request/response traces.
LoggingMiddleware registration: the constructor takes RequestDelegate and ILogger<LoggingMiddleware> (standard UseMiddleware<T> pattern).
Tests and CI
- Tests:
dotnet testonYouBIM.Common.Middlewares.UnitTests(logging middleware, combination withUseCustomErrors, andAppSettingwithConfigurationBuilder+ JSON streams). - Bitbucket Pipelines: the
developbranch runsdotnet build+dotnet pack+dotnet nuget pushin Release (bitbucket-pipelines.yml), publishingYouBIM.Common.Middlewares.Libto NuGet.org.
Design notes
- Exception middleware emphasizes JSON +
TraceIdfor correlation withLoggingMiddlewarelogs. - Successful responses do not include the full body in logs by default (only for 4xx/5xx), reducing noise and log size.
- The library targets .NET 8. When consuming it from
net8.0services, theMicrosoft.Extensions.*8.0.x packages align without extra work.
Deprecation notice (migration to modern stack)
This library is a legacy observability layer for ASP.NET Core (it targets netcoreapp3.1 and provides custom logging + exception middlewares).
For new services and for modernized net8.0 scaffolding, the recommended approach is:
- Serilog for application and request logging
- OpenTelemetry for tracing/metrics (OTLP exporter)
- ProblemDetails for consistent HTTP error responses (including
traceId)
Projects currently affected (need to be updated)
The following API projects still import and register YouBIM.Common.Middlewares.Lib.Logging.LoggingMiddleware (and related exception middleware). They should be migrated to the modern stack described above.
D:/GIT proyects/youbim.locations.api/Youbim.Locations.Api/Program.csD:/GIT proyects/workorders.api/src/YouBIM.WorkOrders.Api/Program.csD:/GIT proyects/system.configurations.api/YouBIM.System.Configurations.Api/Program.csD:/GIT proyects/YouBIM.youbim.users.api/YouBIM.YouBIM.Users.Api/Startup.csD:/GIT proyects/YouBIM.youbim.notifications.api/YouBIM.YouBIM.Notifications.Api/Startup.csD:/GIT proyects/YouBIM.youbim.amazons3.api/YouBIM.YouBIM.AmazonS3.Api/Startup.csD:/GIT proyects/YouBIM.youbim.mappingstorage.api/YouBIM.YouBIM.MappingStorage.Api/Startup.csD:/GIT proyects/YouBIM.youbim.documents.api/YouBIM.YouBIM.Documents.Api/Program.csD:/GIT proyects/YouBIM.youbim.documents.api 0/YouBIM.YouBIM.Documents.Api/Startup.cs(duplicate checkout)D:/GIT proyects/YouBIM/YouBIM.youbim.amazons3.api/YouBIM.YouBIM.AmazonS3.Api/Startup.cs(duplicate checkout)D:/GIT proyects/YouBIM/YouBIM.youbim.documents.api/YouBIM.YouBIM.Documents.Api/Startup.cs(duplicate checkout)
You can remove usage of the middlewares provided here (LoggingMiddleware, CustomExceptionHandlerMiddleware, and/or UseCustomErrors(...)) and configure the stack at Program.cs instead (see the youbim.common.scaffolding.api.8 template).
Minimal migration checklist
Remove middleware usage
- Remove
app.UseMiddleware<LoggingMiddleware>(); - Remove
app.UseMiddleware<CustomExceptionHandlerMiddleware>(); - Remove
UseCustomErrors(...)usage (if present).
- Remove
Add ProblemDetails
- Register
AddProblemDetails(...)and ensure you addtraceIdtoProblemDetails.Extensions.
- Register
Enable Serilog
- Configure
builder.Host.UseSerilog(...)and optionallyapp.UseSerilogRequestLogging().
- Configure
Enable OpenTelemetry
- Register
builder.Services.AddOpenTelemetry() - Add ASP.NET Core + HttpClient instrumentation
- Export via OTLP (
OpenTelemetry:Otlp:Endpoint).
- Register
Minimal Program.cs example (modern stack)
// 1) Serilog as the main logger
builder.Host.UseSerilog((context, services, loggerConfiguration) =>
{
loggerConfiguration
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext()
.WriteTo.Console();
});
// 2) ProblemDetails (add traceId consistently)
builder.Services.AddProblemDetails(options =>
{
options.CustomizeProblemDetails = ctx =>
{
ctx.ProblemDetails.Extensions["traceId"] = ctx.HttpContext.TraceIdentifier;
};
});
// 3) OpenTelemetry (tracing/metrics via OTLP)
builder.Services.AddOpenTelemetry()
.WithTracing(t =>
{
t.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddOtlpExporter();
})
.WithMetrics(m =>
{
m.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddOtlpExporter();
});
var app = builder.Build();
// Replace legacy exception middleware
app.UseExceptionHandler();
app.UseStatusCodePages();
// Request logging
app.UseSerilogRequestLogging();
What you will lose / change
- This middleware library logs request/response bodies on error. In the new stack, request body logging is not automatic by default; you will typically rely on logs/traces/structured metadata instead (and enable body capture only if strictly needed).
- Error responses move from the custom
ResponseErrorJSON contract toProblemDetails(RFC 7807), withtraceIdadded consistently.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Newtonsoft.Json (>= 13.0.4)
- Serilog.AspNetCore (>= 10.0.0)
- Serilog.Formatting.Compact (>= 3.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.