Refactor DIExtensions and add exception handling middleware

- Improved documentation in DIExtensions.cs for clarity.
- Added project reference to DigitalData.Core.Exceptions.
- Updated solution file to include DigitalData.Core.Exceptions.
- Introduced ExceptionHandlingMiddleware for global exception handling.
- Added BadRequestException and NotFoundException classes.
- Created DigitalData.Core.Exceptions project with .NET 7.0, 8.0, and 9.0 support.
This commit is contained in:
Developer 02 2025-05-16 15:37:21 +02:00
parent 55eb250d7e
commit eae0d9f913
7 changed files with 185 additions and 44 deletions

View File

@ -1,53 +1,50 @@
using Microsoft.AspNetCore.Builder; namespace DigitalData.Core.API;
using System.Configuration;
namespace DigitalData.Core.API /// <summary>
/// Provides extension methods for adding middleware to the application's request pipeline.
/// </summary>
public static class DIExtensions
{ {
/// <summary> /// <summary>
/// Provides extension methods for adding middleware to the application's request pipeline. /// Adds the <see cref="CSPMiddleware"/> to the application's request pipeline to include
/// Content Security Policy (CSP) headers in the HTTP response.
/// </summary> /// </summary>
public static class DIExtensions /// <param name="app">The application builder.</param>
{ /// <param name="policy">
/// <summary> /// The CSP policy string with placeholders. The first format parameter {0} will be replaced
/// Adds the <see cref="CSPMiddleware"/> to the application's request pipeline to include /// by the nonce value.
/// Content Security Policy (CSP) headers in the HTTP response. /// </param>
/// </summary> /// <returns>The application builder with the CSP middleware added.</returns>
/// <param name="app">The application builder.</param> public static IApplicationBuilder UseCSPMiddleware(this IApplicationBuilder app, string policy)
/// <param name="policy"> => app.UseMiddleware<CSPMiddleware>(policy);
/// The CSP policy string with placeholders. The first format parameter {0} will be replaced
/// by the nonce value.
/// </param>
/// <returns>The application builder with the CSP middleware added.</returns>
public static IApplicationBuilder UseCSPMiddleware(this IApplicationBuilder app, string policy)
=> app.UseMiddleware<CSPMiddleware>(policy);
/// <summary> /// <summary>
/// Checks if the DiP (Development in Production) mode is enabled for the WebApplicationBuilder. /// Checks if the DiP (Development in Production) mode is enabled for the WebApplicationBuilder.
/// </summary> /// </summary>
/// <param name="builder">The WebApplicationBuilder instance.</param> /// <param name="builder">The WebApplicationBuilder instance.</param>
/// <returns>True if DiP mode is enabled; otherwise, false.</returns> /// <returns>True if DiP mode is enabled; otherwise, false.</returns>
public static bool IsDiP(this WebApplicationBuilder builder) => builder.Configuration.GetValue<bool>("DiPMode"); public static bool IsDiP(this WebApplicationBuilder builder) => builder.Configuration.GetValue<bool>("DiPMode");
/// <summary> /// <summary>
/// Checks if the DiP (Development in Production) mode is enabled for the WebApplication. /// Checks if the DiP (Development in Production) mode is enabled for the WebApplication.
/// </summary> /// </summary>
/// <param name="app">The WebApplication instance.</param> /// <param name="app">The WebApplication instance.</param>
/// <returns>True if DiP mode is enabled; otherwise, false.</returns> /// <returns>True if DiP mode is enabled; otherwise, false.</returns>
public static bool IsDiP(this WebApplication app) => app.Configuration.GetValue<bool>("DiPMode"); public static bool IsDiP(this WebApplication app) => app.Configuration.GetValue<bool>("DiPMode");
/// <summary> /// <summary>
/// Checks if the environment is Development or DiP (Development in Production) mode is enabled for the WebApplicationBuilder. /// Checks if the environment is Development or DiP (Development in Production) mode is enabled for the WebApplicationBuilder.
/// </summary> /// </summary>
/// <param name="builder">The WebApplicationBuilder instance.</param> /// <param name="builder">The WebApplicationBuilder instance.</param>
/// <returns>True if the environment is Development or DiP mode is enabled; otherwise, false.</returns> /// <returns>True if the environment is Development or DiP mode is enabled; otherwise, false.</returns>
public static bool IsDevOrDiP(this WebApplicationBuilder builder) => builder.Environment.IsDevelopment() || builder.IsDiP(); public static bool IsDevOrDiP(this WebApplicationBuilder builder) => builder.Environment.IsDevelopment() || builder.IsDiP();
/// <summary> /// <summary>
/// Checks if the environment is Development or DiP (Development in Production) mode is enabled for the WebApplication. /// Checks if the environment is Development or DiP (Development in Production) mode is enabled for the WebApplication.
/// </summary> /// </summary>
/// <param name="app">The WebApplication instance.</param> /// <param name="app">The WebApplication instance.</param>
/// <returns>True if the environment is Development or DiP mode is enabled; otherwise, false.</returns> /// <returns>True if the environment is Development or DiP mode is enabled; otherwise, false.</returns>
public static bool IsDevOrDiP(this WebApplication app) => app.Environment.IsDevelopment() || app.IsDiP(); public static bool IsDevOrDiP(this WebApplication app) => app.Environment.IsDevelopment() || app.IsDiP();
/// <summary> /// <summary>
/// Configures the services with options from the specified section of the appsettings.json file. /// Configures the services with options from the specified section of the appsettings.json file.
@ -65,5 +62,4 @@ namespace DigitalData.Core.API
builder.Services.Configure<T>(section); builder.Services.Configure<T>(section);
return builder; return builder;
} }
} }
}

View File

@ -33,6 +33,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\DigitalData.Core.Application\DigitalData.Core.Application.csproj" /> <ProjectReference Include="..\DigitalData.Core.Application\DigitalData.Core.Application.csproj" />
<ProjectReference Include="..\DigitalData.Core.Exceptions\DigitalData.Core.Exceptions.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -0,0 +1,84 @@
namespace DigitalData.Core.API;
using DigitalData.Core.Exceptions;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Net;
using System.Text.Json;
/// <summary>
/// Middleware for handling exceptions globally in the application.
/// Captures exceptions thrown during the request pipeline execution,
/// logs them, and returns an appropriate HTTP response with a JSON error message.
/// </summary>
public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="ExceptionHandlingMiddleware"/> class.
/// </summary>
/// <param name="next">The next middleware in the request pipeline.</param>
/// <param name="logger">The logger instance for logging exceptions.</param>
public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
{
_next = next;
_logger = logger;
}
/// <summary>
/// Invokes the middleware to handle the HTTP request.
/// </summary>
/// <param name="context">The HTTP context of the current request.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context); // Continue down the pipeline
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex, _logger);
}
}
/// <summary>
/// Handles exceptions by logging them and writing an appropriate JSON response.
/// </summary>
/// <param name="context">The HTTP context of the current request.</param>
/// <param name="exception">The exception that occurred.</param>
/// <param name="logger">The logger instance for logging the exception.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
private static async Task HandleExceptionAsync(HttpContext context, Exception exception, ILogger logger)
{
context.Response.ContentType = "application/json";
string message;
switch (exception)
{
case BadRequestException badRequestEx:
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
message = badRequestEx.Message;
break;
case NotFoundException notFoundEx:
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
message = notFoundEx.Message;
break;
default:
logger.LogError(exception, "Unhandled exception occurred.");
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
message = "An unexpected error occurred.";
break;
}
await context.Response.WriteAsync(JsonSerializer.Serialize(new
{
message
}));
}
}

View File

@ -0,0 +1,22 @@
namespace DigitalData.Core.Exceptions;
/// <summary>
/// Represents an exception that is thrown when a bad request is encountered.
/// </summary>
public class BadRequestException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="BadRequestException"/> class.
/// </summary>
public BadRequestException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BadRequestException"/> class with a specified error message.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public BadRequestException(string? message) : base(message)
{
}
}

View File

@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net7.0;net8.0;net9.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,22 @@
namespace DigitalData.Core.Exceptions;
/// <summary>
/// Represents an exception that is thrown when a requested resource is not found.
/// </summary>
public class NotFoundException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="NotFoundException"/> class.
/// </summary>
public NotFoundException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="NotFoundException"/> class with a specified error message.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public NotFoundException(string? message) : base(message)
{
}
}

View File

@ -39,6 +39,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DigitalData.Core.Infrastruc
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Infrastructure", "Infrastructure", "{41795B74-A757-4E93-B907-83BFF04EEE5C}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Infrastructure", "Infrastructure", "{41795B74-A757-4E93-B907-83BFF04EEE5C}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DigitalData.Core.Exceptions", "DigitalData.Core.Exceptions\DigitalData.Core.Exceptions.csproj", "{BAEF6CC9-4FE2-4E3F-9D32-911C9E8CCFB4}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@ -100,6 +102,10 @@ Global
{CE00E1F7-2771-4D9C-88FB-E564894E539E}.Debug|Any CPU.Build.0 = Release|Any CPU {CE00E1F7-2771-4D9C-88FB-E564894E539E}.Debug|Any CPU.Build.0 = Release|Any CPU
{CE00E1F7-2771-4D9C-88FB-E564894E539E}.Release|Any CPU.ActiveCfg = Release|Any CPU {CE00E1F7-2771-4D9C-88FB-E564894E539E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CE00E1F7-2771-4D9C-88FB-E564894E539E}.Release|Any CPU.Build.0 = Release|Any CPU {CE00E1F7-2771-4D9C-88FB-E564894E539E}.Release|Any CPU.Build.0 = Release|Any CPU
{BAEF6CC9-4FE2-4E3F-9D32-911C9E8CCFB4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BAEF6CC9-4FE2-4E3F-9D32-911C9E8CCFB4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BAEF6CC9-4FE2-4E3F-9D32-911C9E8CCFB4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BAEF6CC9-4FE2-4E3F-9D32-911C9E8CCFB4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
@ -121,6 +127,7 @@ Global
{C9266749-9504-4EA9-938F-F083357B60B7} = {72CBAFBA-55CC-49C9-A484-F8F4550054CB} {C9266749-9504-4EA9-938F-F083357B60B7} = {72CBAFBA-55CC-49C9-A484-F8F4550054CB}
{CE00E1F7-2771-4D9C-88FB-E564894E539E} = {41795B74-A757-4E93-B907-83BFF04EEE5C} {CE00E1F7-2771-4D9C-88FB-E564894E539E} = {41795B74-A757-4E93-B907-83BFF04EEE5C}
{41795B74-A757-4E93-B907-83BFF04EEE5C} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} {41795B74-A757-4E93-B907-83BFF04EEE5C} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
{BAEF6CC9-4FE2-4E3F-9D32-911C9E8CCFB4} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
EndGlobalSection EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {8E2C3187-F848-493A-9E79-56D20DDCAC94} SolutionGuid = {8E2C3187-F848-493A-9E79-56D20DDCAC94}