| | | 1 | | namespace ZhEaIsNsAaBn.Utilities.APIExceptionHandlers; |
| | | 2 | | |
| | | 3 | | /// <summary> |
| | | 4 | | /// Writes problem-details responses (status-code pages, <c>Results.Problem</c>, …) as the <see cref="BaseResponse"/> en |
| | | 5 | | /// response's own status, one error whose code is the status name (e.g. <c>NotFound</c>), and the trace and transaction |
| | | 6 | | /// Registered ahead of the default writer by <c>AddCustomExceptionHandlers().Build()</c>. |
| | | 7 | | /// </summary> |
| | | 8 | | internal sealed class BaseResponseProblemDetailsWriter : IProblemDetailsWriter |
| | | 9 | | { |
| | 4 | 10 | | private static readonly JsonSerializerOptions Compact = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, |
| | 4 | 11 | | private static readonly JsonSerializerOptions Indented = new( Compact ) { WriteIndented = true }; |
| | | 12 | | |
| | | 13 | | private readonly IWebHostEnvironment _environment; |
| | | 14 | | |
| | | 15 | | |
| | 192 | 16 | | public BaseResponseProblemDetailsWriter( IWebHostEnvironment environment ) => _environment = environment; |
| | | 17 | | |
| | | 18 | | |
| | 4 | 19 | | public bool CanWrite( ProblemDetailsContext context ) => true; |
| | | 20 | | |
| | | 21 | | public async ValueTask WriteAsync( ProblemDetailsContext context ) |
| | | 22 | | { |
| | 4 | 23 | | ArgumentNullException.ThrowIfNull( context ); |
| | | 24 | | |
| | 4 | 25 | | var httpContext = context.HttpContext; |
| | 4 | 26 | | var status = context.ProblemDetails.Status ?? httpContext.Response.StatusCode; |
| | 4 | 27 | | var code = Enum.IsDefined( typeof( HttpStatusCode ), status ) ? ( (HttpStatusCode) status ).ToString() : |
| | 4 | 28 | | var message = context.ProblemDetails.Title ?? context.ProblemDetails.Detail ?? $"The request failed with HTT |
| | | 29 | | |
| | 4 | 30 | | var response = new BaseResponse |
| | 4 | 31 | | { |
| | 4 | 32 | | Status = status, |
| | 4 | 33 | | Errors = [ new Error( code, "Http", $"فشل الطلب (رمز الحالة {status}).", message ) ], |
| | 4 | 34 | | TraceId = System.Diagnostics.Activity.Current?.TraceId.ToString() ?? httpContext.TraceIde |
| | 4 | 35 | | TransId = httpContext.Items[ "transId" ]?.ToString() ?? httpContext.Request.Headers[ "Tra |
| | 4 | 36 | | }; |
| | | 37 | | |
| | | 38 | | |
| | 4 | 39 | | httpContext.Response.StatusCode = status; |
| | 4 | 40 | | httpContext.Response.ContentType = "application/json"; |
| | | 41 | | |
| | | 42 | | |
| | 4 | 43 | | await httpContext.Response.WriteAsync( JsonSerializer.Serialize( response, _environment.IsDevelopment() ? Indent |
| | 4 | 44 | | } |
| | | 45 | | } |