MiddlewareExceptionHandler 1.1.1

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

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 {RequestHost} {RequestScheme}";

    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}] >> {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.  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. 
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.1.1 674 3/1/2025
1.1.0 84 2/28/2025
1.0.8 680 5/31/2024
1.0.7 167 4/19/2024
1.0.6 90 4/19/2024
1.0.5 109 4/19/2024
1.0.4 90 4/18/2024
1.0.3 86 4/18/2024
1.0.2 118 4/15/2024
1.0.1 94 4/15/2024
1.0.0 103 4/15/2024

- Changed the minimum log level from Information to Error in the GlobalExceptionHandlingMiddleware.
- Changed the minimum log level from Information to Error in the StandardMessageResult.
- Added the status code to the log context for all LogError calls.
- Added a standard user message: "Unauthorized" for UnauthorizedAccessException.