-
Notifications
You must be signed in to change notification settings - Fork 110
/
ProblemDetailsMiddleware.cs
232 lines (190 loc) · 7.89 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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
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 Microsoft.Extensions.StackTrace.Sources;
using Microsoft.Net.Http.Headers;
using MvcProblemDetails = Microsoft.AspNetCore.Mvc.ProblemDetails;
namespace Hellang.Middleware.ProblemDetails
{
public class ProblemDetailsMiddleware
{
private static readonly ActionDescriptor EmptyActionDescriptor = new ActionDescriptor();
private static readonly RouteData EmptyRouteData = new RouteData();
private static readonly HashSet<string> CorsHeaderNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
HeaderNames.AccessControlAllowCredentials,
HeaderNames.AccessControlAllowHeaders,
HeaderNames.AccessControlAllowMethods,
HeaderNames.AccessControlAllowOrigin,
HeaderNames.AccessControlExposeHeaders,
HeaderNames.AccessControlMaxAge,
};
public ProblemDetailsMiddleware(
RequestDelegate next,
IOptions<ProblemDetailsOptions> options,
IActionResultExecutor<ObjectResult> executor,
IHostingEnvironment environment,
ILogger<ProblemDetailsMiddleware> logger)
{
Next = next;
Options = options.Value;
Executor = executor;
Logger = logger;
var fileProvider = Options.FileProvider ?? environment.ContentRootFileProvider;
DetailsProvider = new ExceptionDetailsProvider(fileProvider, Options.SourceCodeLineCount);
}
private RequestDelegate Next { get; }
private ProblemDetailsOptions Options { get; }
private IActionResultExecutor<ObjectResult> Executor { get; }
private ILogger<ProblemDetailsMiddleware> Logger { get; }
private ExceptionDetailsProvider DetailsProvider { get; }
public async Task Invoke(HttpContext context)
{
try
{
await Next(context);
if (IsProblem(context))
{
if (context.Response.HasStarted)
{
Logger.ResponseStarted();
return;
}
ClearResponse(context, context.Response.StatusCode);
var details = GetDetails(context, error: null);
await WriteProblemDetails(context, details);
}
}
catch (Exception error)
{
Logger.UnhandledException(error);
if (context.Response.HasStarted)
{
Logger.ResponseStarted();
throw; // Re-throw the original exception if we can't handle it properly.
}
try
{
ClearResponse(context, StatusCodes.Status500InternalServerError);
var details = GetDetails(context, error);
await WriteProblemDetails(context, details);
return;
}
catch (Exception inner)
{
// If we fail to write a problem response, we log the exception and throw the original below.
Logger.ProblemDetailsMiddlewareException(inner);
}
throw; // Re-throw the original exception if we can't handle it properly.
}
}
private MvcProblemDetails GetDetails(HttpContext context, Exception error)
{
if (error == null)
{
return new StatusCodeProblemDetails(context.Response.StatusCode);
}
var result = GetProblemDetails(error);
// We don't want to leak exception details unless it's configured,
// even if the user mapped the exception into ExceptionProblemDetails.
if (result is ExceptionProblemDetails ex)
{
if (Options.IncludeExceptionDetails(context))
{
try
{
var details = DetailsProvider.GetDetails(ex.Error);
return new DeveloperProblemDetails(ex, details);
}
catch (Exception e)
{
// Failed to get exception details for the specific exception.
// Fall back to generic status code problem details below.
Logger.ProblemDetailsMiddlewareException(e);
}
}
return new StatusCodeProblemDetails(ex.Status ?? context.Response.StatusCode);
}
return result;
}
private MvcProblemDetails GetProblemDetails(Exception error)
{
if (error is ProblemDetailsException problem)
{
// The user has already provided a valid problem details object.
return problem.Details;
}
if (Options.TryMapProblemDetails(error, out var result))
{
// The user has set up a mapping for the specific exception type.
return result;
}
// Fall back to the generic exception problem details.
return new ExceptionProblemDetails(error);
}
private Task WriteProblemDetails(HttpContext context, MvcProblemDetails details)
{
var routeData = context.GetRouteData() ?? EmptyRouteData;
var actionContext = new ActionContext(context, routeData, EmptyActionDescriptor);
var result = new ObjectResult(details)
{
StatusCode = details.Status ?? context.Response.StatusCode,
DeclaredType = details.GetType(),
};
result.ContentTypes.Add("application/problem+json");
result.ContentTypes.Add("application/problem+xml");
return Executor.ExecuteAsync(actionContext, result);
}
private static bool IsProblem(HttpContext context)
{
if (context.Response.StatusCode < 400)
{
return false;
}
if (context.Response.StatusCode >= 600)
{
return false;
}
if (context.Response.ContentLength.HasValue)
{
return false;
}
if (string.IsNullOrEmpty(context.Response.ContentType))
{
return true;
}
return false;
}
private static void ClearResponse(HttpContext context, int statusCode)
{
var headers = new HeaderDictionary();
// Make sure problem responses are never cached.
headers.Append(HeaderNames.CacheControl, "no-cache, no-store, must-revalidate");
headers.Append(HeaderNames.Pragma, "no-cache");
headers.Append(HeaderNames.Expires, "0");
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 (CorsHeaderNames.Contains(header.Key))
{
headers.Add(header);
}
}
context.Response.Clear();
context.Response.StatusCode = statusCode;
foreach (var header in headers)
{
context.Response.Headers.Add(header);
}
}
}
}