MiddlewareExceptionHandler 1.1.1
dotnet add package MiddlewareExceptionHandler --version 1.1.1
NuGet\Install-Package MiddlewareExceptionHandler -Version 1.1.1
<PackageReference Include="MiddlewareExceptionHandler" Version="1.1.1" />
<PackageVersion Include="MiddlewareExceptionHandler" Version="1.1.1" />
<PackageReference Include="MiddlewareExceptionHandler" />
paket add MiddlewareExceptionHandler --version 1.1.1
#r "nuget: MiddlewareExceptionHandler, 1.1.1"
#:package MiddlewareExceptionHandler@1.1.1
#addin nuget:?package=MiddlewareExceptionHandler&version=1.1.1
#tool nuget:?package=MiddlewareExceptionHandler&version=1.1.1
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 | Versions 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. |
-
net7.0
- Serilog.AspNetCore (>= 8.0.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
- 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.