SweetMeSoft.Middleware 1.10.105

dotnet add package SweetMeSoft.Middleware --version 1.10.105
                    
NuGet\Install-Package SweetMeSoft.Middleware -Version 1.10.105
                    
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="SweetMeSoft.Middleware" Version="1.10.105" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="SweetMeSoft.Middleware" Version="1.10.105" />
                    
Directory.Packages.props
<PackageReference Include="SweetMeSoft.Middleware" />
                    
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 SweetMeSoft.Middleware --version 1.10.105
                    
#r "nuget: SweetMeSoft.Middleware, 1.10.105"
                    
#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 SweetMeSoft.Middleware@1.10.105
                    
#: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=SweetMeSoft.Middleware&version=1.10.105
                    
Install as a Cake Addin
#tool nuget:?package=SweetMeSoft.Middleware&version=1.10.105
                    
Install as a Cake Tool

SweetMeSoft.Middleware

Librería con un conjunto de Middlewares y servicios para aplicaciones ASP.NET Core.

Descripción

SweetMeSoft.Middleware es una librería para .NET Standard 2.1 que ofrece componentes para ASP.NET Core, diseñados para centralizar la gestión de errores, registrar peticiones y facilitar el acceso a servicios a través de un patrón Factory.

Componentes Principales

1. ErrorHandlerMiddleware

Un middleware para la gestión global de excepciones. Captura las excepciones no controladas en la aplicación y las transforma en una respuesta JSON estandarizada con formato ProblemDetails.

Comportamiento:

  • AppException (excepción personalizada): Devuelve 400 Bad Request.
  • KeyNotFoundException: Devuelve 404 Not Found.
  • Cualquier otra excepción: Devuelve 500 Internal Server Error.

2. RequestLoggingMiddleware

Un middleware para registrar los detalles de las peticiones y respuestas. Es altamente configurable, ya que permite inyectar una función de logging personalizada.

Comportamiento:

  • Intercepta la petición y la respuesta para leer sus cuerpos.
  • Invoca una función writeLog que le pasas en el constructor, entregándole el HttpContext, el cuerpo de la respuesta, el código de estado y el cuerpo de la petición.
  • También incluye su propio manejo de excepciones, que registra y formatea como ProblemDetails.

3. ServiceFactory

Una implementación del patrón Factory (IServiceFactory) que se integra con el contenedor de inyección de dependencias de ASP.NET Core. Permite desacoplar la lógica de negocio de la implementación directa de IServiceProvider.

Dependencias

Instalación

dotnet add package SweetMeSoft.Middleware

Uso

Configuración en Startup.cs

Debes registrar los componentes en tu clase Startup.cs (o Program.cs en .NET 6+).

using SweetMeSoft.Middleware;
using SweetMeSoft.Middleware.Interface;
using SweetMeSoft.Middleware.Service;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // ... otros servicios
        
        // 1. Registrar el ServiceFactory
        services.AddScoped<IServiceFactory, ServiceFactory>();
        
        // ... registrar tus propios servicios (ej. IMyService, MyService)
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // ...
        
        // 2. Añadir los middlewares al pipeline
        // Es importante el orden. El ErrorHandler generalmente va primero.
        app.UseMiddleware<ErrorHandlerMiddleware>();

        // Para el RequestLoggingMiddleware, debes proporcionar tu propia lógica de logging
        app.UseMiddleware<RequestLoggingMiddleware>(async (httpContext, responseBody, statusCode, requestBody) => 
        {
            // Tu lógica de logging aquí
            // Ejemplo:
            Console.WriteLine($"Request: {requestBody} | Status: {statusCode} | Response: {responseBody}");
            await Task.CompletedTask;
        });

        app.UseRouting();
        // ...
    }
}

Uso de IServiceFactory en un Controlador

Inyecta IServiceFactory en tus controladores o servicios para obtener instancias de otros servicios.

using SweetMeSoft.Middleware.Interface;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("[controller]")]
public class MyController : ControllerBase
{
    private readonly IMyService myService;

    // Inyecta la factory en el constructor
    public MyController(IServiceFactory factory)
    {
        // Usa la factory para obtener el servicio que necesitas
        this.myService = factory.Get<IMyService>();
    }

    [HttpGet]
    public IActionResult Get()
    {
        var data = myService.GetData();
        return Ok(data);
    }
}

Lanzar Excepciones Personalizadas

Desde tu lógica de negocio, puedes lanzar una AppException para generar una respuesta 400 Bad Request controlada.

public class MyService : IMyService
{
    public string GetData()
    {
        // ...
        if (string.IsNullOrEmpty(someValue))
        {
            // Esto será capturado por ErrorHandlerMiddleware
            throw new AppException("El valor no puede ser nulo.");
        }
        // ...
    }
}

Licencia

Este proyecto está bajo la licencia MIT.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  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. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos 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
1.10.105 76 9/5/2025
1.10.104 153 4/29/2025
1.10.103 140 2/27/2025
1.10.102 121 2/27/2025
1.10.101 199 10/12/2023
1.10.1 152 10/12/2023