-
Notifications
You must be signed in to change notification settings - Fork 110
/
ProblemDetailsMiddleware.cs
195 lines (155 loc) · 6.42 KB
/
ProblemDetailsMiddleware.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
using System;
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MvcProblemDetails = Microsoft.AspNetCore.Mvc.ProblemDetails;
namespace Hellang.Middleware.ProblemDetails
{
public class ProblemDetailsMiddleware
{
private const string DiagnosticListenerKey = "Microsoft.AspNetCore.Diagnostics.HandledException";
private static readonly ActionDescriptor EmptyActionDescriptor = new();
private static readonly RouteData EmptyRouteData = new();
public ProblemDetailsMiddleware(
RequestDelegate next,
IOptions<ProblemDetailsOptions> options,
ProblemDetailsFactory factory,
IActionResultExecutor<ObjectResult> executor,
ILogger<ProblemDetailsMiddleware> logger,
DiagnosticListener diagnosticListener)
{
Next = next;
Factory = factory;
Options = options.Value;
Executor = executor;
Logger = logger;
DiagnosticListener = diagnosticListener;
}
private RequestDelegate Next { get; }
private ProblemDetailsFactory Factory { get; }
private ProblemDetailsOptions Options { get; }
private IActionResultExecutor<ObjectResult> Executor { get; }
private ILogger<ProblemDetailsMiddleware> Logger { get; }
private DiagnosticListener DiagnosticListener { get; }
public async Task Invoke(HttpContext context)
{
ExceptionDispatchInfo? edi = null;
try
{
await Next(context);
if (Options.IsProblem(context))
{
await HandleProblem(context);
}
}
catch (Exception ex)
{
edi = ExceptionDispatchInfo.Capture(ex);
}
if (edi != null)
{
await HandleException(context, edi);
}
}
private Task HandleProblem(HttpContext context)
{
if (context.Response.HasStarted)
{
Logger.ResponseStarted();
return Task.CompletedTask;
}
ClearResponse(context, context.Response.StatusCode);
var details = Factory.CreateProblemDetails(context);
return WriteProblemDetails(context, details);
}
private async Task HandleException(HttpContext context, ExceptionDispatchInfo edi)
{
if (context.Response.HasStarted)
{
Logger.ResponseStarted();
edi.Throw(); // Re-throw the original exception if we can't handle it properly.
}
try
{
var error = edi.SourceException;
var feature = new ExceptionHandlerFeature
{
Path = context.Request.Path,
Error = error,
};
ClearResponse(context, StatusCodes.Status500InternalServerError);
context.Features.Set<IExceptionHandlerPathFeature>(feature);
context.Features.Set<IExceptionHandlerFeature>(feature);
var details = Factory.CreateExceptionProblemDetails(context, error);
if (details != null) // Don't handle the exception if we can't or don't want to convert it to ProblemDetails
{
if (Options.ShouldLogUnhandledException(context, error, details))
{
Logger.UnhandledException(error);
}
await WriteProblemDetails(context, details);
if (DiagnosticListener.IsEnabled() && DiagnosticListener.IsEnabled(DiagnosticListenerKey))
{
DiagnosticListener.Write(DiagnosticListenerKey, new { httpContext = context, exception = error });
}
if (!Options.ShouldRethrowException(context, error))
{
return;
}
}
else
{
Logger.IgnoredException(error);
}
}
catch (Exception inner)
{
// If we fail to write a problem response, we log the exception and throw the original below.
Logger.ProblemDetailsMiddlewareException(inner);
}
edi.Throw(); // Re-throw the original exception if we can't handle it properly or it's intended.
}
private async Task WriteProblemDetails(HttpContext context, MvcProblemDetails details)
{
Options.CallBeforeWriteHook(context, details);
var routeData = context.GetRouteData() ?? EmptyRouteData;
var actionContext = new ActionContext(context, routeData, EmptyActionDescriptor);
var result = new ObjectResult(details)
{
StatusCode = details.Status ?? context.Response.StatusCode,
ContentTypes = Options.ContentTypes.Clone(),
};
await Executor.ExecuteAsync(actionContext, result);
await context.Response.CompleteAsync();
}
private void ClearResponse(HttpContext context, int statusCode)
{
var headers = new HeaderDictionary();
// Make sure problem responses are never cached.
Options.AppendCacheHeaders(context, headers);
foreach (var header in context.Response.Headers)
{
// Because the CORS middleware adds all the headers early in the pipeline,
// we want to copy over the existing Access-Control-* headers after resetting the response.
if (Options.AllowedHeaderNames.Contains(header.Key))
{
headers.Add(header);
}
}
context.Response.Clear();
context.Response.StatusCode = statusCode;
foreach (var header in headers)
{
context.Response.Headers.Add(header);
}
}
}
}