MiddlewareExceptionHandler 1.0.8

dotnet add package MiddlewareExceptionHandler --version 1.0.8
NuGet\Install-Package MiddlewareExceptionHandler -Version 1.0.8
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="MiddlewareExceptionHandler" Version="1.0.8" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add MiddlewareExceptionHandler --version 1.0.8
#r "nuget: MiddlewareExceptionHandler, 1.0.8"
#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.
// Install MiddlewareExceptionHandler as a Cake Addin
#addin nuget:?package=MiddlewareExceptionHandler&version=1.0.8

// Install MiddlewareExceptionHandler as a Cake Tool
#tool nuget:?package=MiddlewareExceptionHandler&version=1.0.8

Configuration

Program.cs

1. Middleware service

builder.Services.AddScoped<GlobalExceptionHandlingMiddleware>();

2. Serilog

builder.Host.UseSerilog((context, configuration) => configuration.ReadFrom.Configuration(context.Configuration));

3. Serilog middleware
app.UseSerilogRequestLogging(options =>
{
    options.MessageTemplate = "HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms";

    options.GetLevel = (httpContext, elapsed, ex) =>
    {
        if (httpContext.Response.StatusCode >= StatusCodes.Status400BadRequest)
        {
            return LogEventLevel.Error;
        }

        return LogEventLevel.Information;
    };

    // Customize the request completion event
    options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
    {
        diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
        diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
    };
});
4. Middleware

app.UseMiddleware<GlobalExceptionHandlingMiddleware>();

Api Response Model

   public class ApiResponseModel or ApiResponseModel<T>
   {
       public HttpStatusCode status { get; set; }
       public DateTime date { get; set; }
       public string? systemMessage { get; set; }
       public string? userMessage { get; set; }
       public object? payload { get; set; } or  public T? payload { get; set; }
   }

Controllers

Change controller inheritance with: BaseApiController and inject ILogger<YourController> _logger;

 public YourController(ILogger<YourController> logger) : base(logger)
 {
     _logger = logger;
 }
 

Use StandardMessageResult to handle your api response;

        public async Task<ActionResult<ApiResponseModel<YourTypeObject>> YourApiMethod()
        {
            try
            {
              /// Code

                return StandardMessageResult(HttpStatusCode.OK, userMessage:"Client Message", result: YourResultObject);
            }
            catch (Exception ex)
            {
                return StandardMessageResult(HttpStatusCode.ErrorCode, exception: ex, userMessage:"Client Message", systemMessage:"Internal Message");
            }
        }

In appsettings.json


  "Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "File",
        "Args": {
          "path": "Logs/log-.txt",
          "rollingInterval": "Day",
          "rollOnFileSizeLimit": true,
          "outputTemplate": "{Level:w5} [{Timestamp:yyyy-MM-dd HH:mm:ss,fff}] [{UserId}] [{ResourceId}] >> {Message}{NewLine}{Exception}",
          "formatter": "Serilog.Formatting.Json.JsonFormatter"
        }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
    "Properties": {
      "Application": "WebApi",
      "Environment": "Production"
    }
  },
Product Compatible and additional computed target framework versions.
.NET net7.0 is compatible.  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. 
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.0.8 73 5/31/2024
1.0.7 133 4/19/2024
1.0.6 61 4/19/2024
1.0.5 64 4/19/2024
1.0.4 58 4/18/2024
1.0.3 60 4/18/2024
1.0.2 74 4/15/2024
1.0.1 68 4/15/2024
1.0.0 74 4/15/2024