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
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="YouBIM.Common.Middlewares.Lib" Version="10.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="YouBIM.Common.Middlewares.Lib" Version="10.0.0" />
                    
Directory.Packages.props
<PackageReference Include="YouBIM.Common.Middlewares.Lib" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add YouBIM.Common.Middlewares.Lib --version 10.0.0
                    
#r "nuget: YouBIM.Common.Middlewares.Lib, 10.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package YouBIM.Common.Middlewares.Lib@10.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=YouBIM.Common.Middlewares.Lib&version=10.0.0
                    
Install as a Cake Addin
#tool nuget:?package=YouBIM.Common.Middlewares.Lib&version=10.0.0
                    
Install as a Cake Tool

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 / Logging 8.0.x, Newtonsoft.Json 13.0.3, Serilog.AspNetCore 8.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 TraceId response header from HttpContext.
    • 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.
  • 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
    Minimal Invoke(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 only Message in 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 reads IExceptionHandlerFeature, logs with GetStringError, and writes ResponseError as JSON with System.Text.Json.
  • CustomExceptionHandlerMiddleware
    Middleware that wraps the pipeline in try/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 uses Build() and ignores the appSettingsFilePath argument on methods (useful in tests with AddJsonStream or in-memory configuration).
    • If _builder is null, configuration is built with ConfigurationBuilder.AddJsonFile(appSettingsFilePath).
    • Methods bind sections by CLR type name (typeof(T).Name), so JSON section keys must match: AuthenticateScheme, Security, ConnectionStrings.
  • Models under StartupSettings.Settings

    • AuthenticateScheme: Active (string collection); GetAuthenticateProviderKey returns the first active entry.
    • Security → JWT: Issuer for GetIssuer.
    • ConnectionStrings → DBConnection: ConnectionString for GetDbConnectionString.

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):

  1. UseExceptionHandler + UseCustomErrors(env) for errors not caught in controllers.
  2. Optional: UseMiddleware<CustomExceptionHandlerMiddleware> if you need an explicit try/catch wrapper.
  3. UseMiddleware<LoggingMiddleware> for request/response traces.

LoggingMiddleware registration: the constructor takes RequestDelegate and ILogger<LoggingMiddleware> (standard UseMiddleware<T> pattern).

Tests and CI

  • Tests: dotnet test on YouBIM.Common.Middlewares.UnitTests (logging middleware, combination with UseCustomErrors, and AppSetting with ConfigurationBuilder + JSON streams).
  • Bitbucket Pipelines: the develop branch runs dotnet build + dotnet pack + dotnet nuget push in Release (bitbucket-pipelines.yml), publishing YouBIM.Common.Middlewares.Lib to NuGet.org.

Design notes

  • Exception middleware emphasizes JSON + TraceId for correlation with LoggingMiddleware logs.
  • 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.0 services, the Microsoft.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.cs
  • D:/GIT proyects/workorders.api/src/YouBIM.WorkOrders.Api/Program.cs
  • D:/GIT proyects/system.configurations.api/YouBIM.System.Configurations.Api/Program.cs
  • D:/GIT proyects/YouBIM.youbim.users.api/YouBIM.YouBIM.Users.Api/Startup.cs
  • D:/GIT proyects/YouBIM.youbim.notifications.api/YouBIM.YouBIM.Notifications.Api/Startup.cs
  • D:/GIT proyects/YouBIM.youbim.amazons3.api/YouBIM.YouBIM.AmazonS3.Api/Startup.cs
  • D:/GIT proyects/YouBIM.youbim.mappingstorage.api/YouBIM.YouBIM.MappingStorage.Api/Startup.cs
  • D:/GIT proyects/YouBIM.youbim.documents.api/YouBIM.YouBIM.Documents.Api/Program.cs
  • D:/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

  1. Remove middleware usage

    • Remove app.UseMiddleware<LoggingMiddleware>();
    • Remove app.UseMiddleware<CustomExceptionHandlerMiddleware>();
    • Remove UseCustomErrors(...) usage (if present).
  2. Add ProblemDetails

    • Register AddProblemDetails(...) and ensure you add traceId to ProblemDetails.Extensions.
  3. Enable Serilog

    • Configure builder.Host.UseSerilog(...) and optionally app.UseSerilogRequestLogging().
  4. Enable OpenTelemetry

    • Register builder.Services.AddOpenTelemetry()
    • Add ASP.NET Core + HttpClient instrumentation
    • Export via OTLP (OpenTelemetry:Otlp:Endpoint).

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 ResponseError JSON contract to ProblemDetails (RFC 7807), with traceId added consistently.
Product 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
10.0.0 49 11/5/2026
1.0.0 50 11/5/2026