| | | 1 | | using System.Diagnostics; |
| | | 2 | | using Microsoft.AspNetCore.Diagnostics; |
| | | 3 | | using Microsoft.Extensions.Options; |
| | | 4 | | using Microsoft.Extensions.Primitives; |
| | | 5 | | using ProjectTemplate.Web.Options; |
| | | 6 | | |
| | | 7 | | namespace ProjectTemplate.Web.ErrorHandling; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Provides extension methods for configuring standardized problem details and exception handling in ASP.NET Core |
| | | 11 | | /// applications. |
| | | 12 | | /// </summary> |
| | | 13 | | /// <remarks>These extensions integrate custom problem details formatting and exception handling into the |
| | | 14 | | /// application's dependency injection and middleware pipelines. They help ensure consistent error responses and |
| | | 15 | | /// traceability across environments.</remarks> |
| | | 16 | | internal static class ProblemDetailsExtensions |
| | | 17 | | { |
| | | 18 | | /// <summary> |
| | | 19 | | /// Adds standardized Problem Details error responses and a custom exception handler to the application's service |
| | | 20 | | /// collection. |
| | | 21 | | /// </summary> |
| | | 22 | | /// <remarks>This method configures Problem Details middleware to include trace and request identifiers in |
| | | 23 | | /// error responses and customizes error details for non-development environments. It also registers a custom |
| | | 24 | | /// exception handler for consistent error formatting.</remarks> |
| | | 25 | | /// <param name="services">The service collection to which Problem Details and the exception handler are added. Cann |
| | | 26 | | /// <param name="webHostEnvironment">The current web hosting environment. Used to determine error detail behavior ba |
| | | 27 | | /// null.</param> |
| | | 28 | | /// <returns>The same service collection instance, enabling method chaining.</returns> |
| | | 29 | | public static IServiceCollection AddApplicationProblemDetails( |
| | | 30 | | this IServiceCollection services, |
| | | 31 | | IWebHostEnvironment webHostEnvironment) |
| | | 32 | | { |
| | 156 | 33 | | ArgumentNullException.ThrowIfNull(services); |
| | 156 | 34 | | ArgumentNullException.ThrowIfNull(webHostEnvironment); |
| | | 35 | | |
| | 156 | 36 | | services.AddExceptionHandler<ProblemDetailsExceptionHandler>(); |
| | | 37 | | |
| | 306 | 38 | | services.AddProblemDetails(options => options.CustomizeProblemDetails = context => |
| | 306 | 39 | | { |
| | 12 | 40 | | string? originalExceptionPath = context.HttpContext.Features |
| | 12 | 41 | | .Get<IExceptionHandlerPathFeature>()? |
| | 12 | 42 | | .Path; |
| | 306 | 43 | | |
| | 12 | 44 | | string? originalStatusCodePath = context.HttpContext.Features |
| | 12 | 45 | | .Get<IStatusCodeReExecuteFeature>()? |
| | 12 | 46 | | .OriginalPath; |
| | 306 | 47 | | |
| | 12 | 48 | | context.ProblemDetails.Instance ??= !string.IsNullOrWhiteSpace(originalExceptionPath) |
| | 12 | 49 | | ? originalExceptionPath |
| | 12 | 50 | | : !string.IsNullOrWhiteSpace(originalStatusCodePath) |
| | 12 | 51 | | ? originalStatusCodePath |
| | 12 | 52 | | : context.HttpContext.Request.Path; |
| | 306 | 53 | | |
| | 12 | 54 | | string correlationId = GetCorrelationId(context.HttpContext); |
| | 306 | 55 | | |
| | 12 | 56 | | Activity? activity = Activity.Current; |
| | 306 | 57 | | |
| | 12 | 58 | | context.ProblemDetails.Extensions["traceId"] = |
| | 12 | 59 | | activity?.TraceId.ToString() ?? context.HttpContext.TraceIdentifier; |
| | 306 | 60 | | |
| | 12 | 61 | | if (activity is not null) |
| | 306 | 62 | | { |
| | 6 | 63 | | context.ProblemDetails.Extensions["spanId"] = activity.SpanId.ToString(); |
| | 306 | 64 | | } |
| | 306 | 65 | | |
| | 12 | 66 | | context.ProblemDetails.Extensions["requestId"] = |
| | 12 | 67 | | context.HttpContext.TraceIdentifier; |
| | 306 | 68 | | |
| | 12 | 69 | | context.ProblemDetails.Extensions["correlationId"] = |
| | 12 | 70 | | correlationId; |
| | 306 | 71 | | |
| | 12 | 72 | | if (!webHostEnvironment.IsDevelopment() && |
| | 12 | 73 | | context.ProblemDetails.Status >= StatusCodes.Status500InternalServerError) |
| | 306 | 74 | | { |
| | 2 | 75 | | context.ProblemDetails.Detail ??= |
| | 2 | 76 | | "An unexpected error occurred. Contact support with the request ID."; |
| | 306 | 77 | | } |
| | 318 | 78 | | }); |
| | | 79 | | |
| | 156 | 80 | | return services; |
| | | 81 | | } |
| | | 82 | | |
| | | 83 | | /// <summary> |
| | | 84 | | /// Configures standardized error handling and problem details middleware for the application based on the current |
| | | 85 | | /// environment. |
| | | 86 | | /// </summary> |
| | | 87 | | /// <remarks>In the development environment, this method enables the developer exception page. In other |
| | | 88 | | /// environments, it configures a generic exception handler and enforces HTTP Strict Transport Security (HSTS). It |
| | | 89 | | /// also sets up status code pages to return problem details responses when appropriate, or redirects to a custom |
| | | 90 | | /// error page otherwise.</remarks> |
| | | 91 | | /// <param name="app">The <see cref="WebApplication"/> instance to configure. Cannot be null.</param> |
| | | 92 | | /// <returns>The configured <see cref="WebApplication"/> instance.</returns> |
| | | 93 | | public static WebApplication UseProblemDetails(this WebApplication app) |
| | | 94 | | { |
| | 142 | 95 | | ArgumentNullException.ThrowIfNull(app); |
| | | 96 | | |
| | 142 | 97 | | if (app.Environment.IsDevelopment()) |
| | | 98 | | { |
| | 0 | 99 | | app.UseDeveloperExceptionPage(); |
| | | 100 | | } |
| | | 101 | | else |
| | | 102 | | { |
| | 142 | 103 | | app.UseExceptionHandler("/Home/Error/500"); |
| | 142 | 104 | | app.UseHsts(); |
| | | 105 | | } |
| | | 106 | | |
| | 142 | 107 | | app.UseWhen( |
| | 142 | 108 | | ProblemDetailsRequestClassifier.ShouldWriteProblemDetails, |
| | 284 | 109 | | branch => branch.UseStatusCodePages()); |
| | | 110 | | |
| | 142 | 111 | | app.UseWhen( |
| | 102 | 112 | | context => !ProblemDetailsRequestClassifier.ShouldWriteProblemDetails(context), |
| | 284 | 113 | | branch => branch.UseStatusCodePagesWithReExecute("/Home/Error/{0}")); |
| | | 114 | | |
| | 142 | 115 | | return app; |
| | | 116 | | } |
| | | 117 | | |
| | | 118 | | private static string GetCorrelationId(HttpContext httpContext) |
| | | 119 | | { |
| | 12 | 120 | | ApplicationRequestLoggingOptions requestLoggingOptions = httpContext.RequestServices |
| | 12 | 121 | | .GetService<IOptions<ApplicationRequestLoggingOptions>>()?.Value |
| | 12 | 122 | | ?? new ApplicationRequestLoggingOptions(); |
| | | 123 | | |
| | 12 | 124 | | if (httpContext.Request.Headers.TryGetValue( |
| | 12 | 125 | | requestLoggingOptions.CorrelationHeaderName, |
| | 12 | 126 | | out StringValues correlationHeaderValues)) |
| | | 127 | | { |
| | 4 | 128 | | string? headerValue = correlationHeaderValues.FirstOrDefault(); |
| | | 129 | | |
| | 4 | 130 | | if (!string.IsNullOrWhiteSpace(headerValue)) |
| | | 131 | | { |
| | 4 | 132 | | string cleanValue = headerValue.Trim(); |
| | | 133 | | |
| | 4 | 134 | | return cleanValue.Length <= 128 |
| | 4 | 135 | | ? cleanValue |
| | 4 | 136 | | : cleanValue[..128]; |
| | | 137 | | } |
| | | 138 | | } |
| | | 139 | | |
| | 8 | 140 | | return httpContext.TraceIdentifier; |
| | | 141 | | } |
| | | 142 | | } |