-
-
Notifications
You must be signed in to change notification settings - Fork 159
/
JsonApiMiddleware.cs
311 lines (253 loc) · 11.9 KB
/
JsonApiMiddleware.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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
using System.Net;
using System.Text.Json;
using JetBrains.Annotations;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Diagnostics;
using JsonApiDotNetCore.Resources.Annotations;
using JsonApiDotNetCore.Serialization.Objects;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
namespace JsonApiDotNetCore.Middleware;
/// <summary>
/// Intercepts HTTP requests to populate injected <see cref="IJsonApiRequest" /> instance for JSON:API requests.
/// </summary>
[PublicAPI]
public sealed class JsonApiMiddleware
{
private static readonly string[] NonOperationsContentTypes = [HeaderConstants.MediaType];
private static readonly MediaTypeHeaderValue[] NonOperationsMediaTypes = [MediaTypeHeaderValue.Parse(HeaderConstants.MediaType)];
private static readonly string[] OperationsContentTypes =
[
HeaderConstants.AtomicOperationsMediaType,
HeaderConstants.RelaxedAtomicOperationsMediaType
];
private static readonly MediaTypeHeaderValue[] OperationsMediaTypes =
[
MediaTypeHeaderValue.Parse(HeaderConstants.AtomicOperationsMediaType),
MediaTypeHeaderValue.Parse(HeaderConstants.RelaxedAtomicOperationsMediaType)
];
private readonly RequestDelegate? _next;
public JsonApiMiddleware(RequestDelegate? next, IHttpContextAccessor httpContextAccessor)
{
ArgumentGuard.NotNull(httpContextAccessor);
_next = next;
var session = new AspNetCodeTimerSession(httpContextAccessor);
CodeTimingSessionManager.Capture(session);
}
public async Task InvokeAsync(HttpContext httpContext, IControllerResourceMapping controllerResourceMapping, IJsonApiOptions options,
IJsonApiRequest request, ILogger<JsonApiMiddleware> logger)
{
ArgumentGuard.NotNull(httpContext);
ArgumentGuard.NotNull(controllerResourceMapping);
ArgumentGuard.NotNull(options);
ArgumentGuard.NotNull(request);
ArgumentGuard.NotNull(logger);
using (CodeTimingSessionManager.Current.Measure("JSON:API middleware"))
{
if (!await ValidateIfMatchHeaderAsync(httpContext, options.SerializerWriteOptions))
{
return;
}
RouteValueDictionary routeValues = httpContext.GetRouteData().Values;
ResourceType? primaryResourceType = CreatePrimaryResourceType(httpContext, controllerResourceMapping);
if (primaryResourceType != null)
{
if (!await ValidateContentTypeHeaderAsync(NonOperationsContentTypes, httpContext, options.SerializerWriteOptions) ||
!await ValidateAcceptHeaderAsync(NonOperationsMediaTypes, httpContext, options.SerializerWriteOptions))
{
return;
}
SetupResourceRequest((JsonApiRequest)request, primaryResourceType, routeValues, httpContext.Request);
httpContext.RegisterJsonApiRequest();
}
else if (IsRouteForOperations(routeValues))
{
if (!await ValidateContentTypeHeaderAsync(OperationsContentTypes, httpContext, options.SerializerWriteOptions) ||
!await ValidateAcceptHeaderAsync(OperationsMediaTypes, httpContext, options.SerializerWriteOptions))
{
return;
}
SetupOperationsRequest((JsonApiRequest)request);
httpContext.RegisterJsonApiRequest();
}
if (_next != null)
{
using (CodeTimingSessionManager.Current.Measure("Subsequent middleware"))
{
await _next(httpContext);
}
}
}
if (CodeTimingSessionManager.IsEnabled)
{
string timingResults = CodeTimingSessionManager.Current.GetResults();
string url = httpContext.Request.GetDisplayUrl();
string method = httpContext.Request.Method.Replace(Environment.NewLine, "");
logger.LogInformation($"Measurement results for {method} {url}:{Environment.NewLine}{timingResults}");
}
}
private async Task<bool> ValidateIfMatchHeaderAsync(HttpContext httpContext, JsonSerializerOptions serializerOptions)
{
if (httpContext.Request.Headers.ContainsKey(HeaderNames.IfMatch))
{
await FlushResponseAsync(httpContext.Response, serializerOptions, new ErrorObject(HttpStatusCode.PreconditionFailed)
{
Title = "Detection of mid-air edit collisions using ETags is not supported.",
Source = new ErrorSource
{
Header = "If-Match"
}
});
return false;
}
return true;
}
private static ResourceType? CreatePrimaryResourceType(HttpContext httpContext, IControllerResourceMapping controllerResourceMapping)
{
Endpoint? endpoint = httpContext.GetEndpoint();
var controllerActionDescriptor = endpoint?.Metadata.GetMetadata<ControllerActionDescriptor>();
return controllerActionDescriptor != null
? controllerResourceMapping.GetResourceTypeForController(controllerActionDescriptor.ControllerTypeInfo)
: null;
}
private static async Task<bool> ValidateContentTypeHeaderAsync(ICollection<string> allowedContentTypes, HttpContext httpContext,
JsonSerializerOptions serializerOptions)
{
string? contentType = httpContext.Request.ContentType;
if (contentType != null && !allowedContentTypes.Contains(contentType, StringComparer.OrdinalIgnoreCase))
{
string allowedValues = string.Join(" or ", allowedContentTypes.Select(value => $"'{value}'"));
await FlushResponseAsync(httpContext.Response, serializerOptions, new ErrorObject(HttpStatusCode.UnsupportedMediaType)
{
Title = "The specified Content-Type header value is not supported.",
Detail = $"Please specify {allowedValues} instead of '{contentType}' for the Content-Type header value.",
Source = new ErrorSource
{
Header = "Content-Type"
}
});
return false;
}
return true;
}
private static async Task<bool> ValidateAcceptHeaderAsync(ICollection<MediaTypeHeaderValue> allowedMediaTypes, HttpContext httpContext,
JsonSerializerOptions serializerOptions)
{
string[] acceptHeaders = httpContext.Request.Headers.GetCommaSeparatedValues("Accept");
if (!acceptHeaders.Any())
{
return true;
}
bool seenCompatibleMediaType = false;
foreach (string acceptHeader in acceptHeaders)
{
if (MediaTypeHeaderValue.TryParse(acceptHeader, out MediaTypeHeaderValue? headerValue))
{
if (headerValue.MediaType == "*/*" || headerValue.MediaType == "application/*")
{
seenCompatibleMediaType = true;
break;
}
headerValue.Quality = null;
if (allowedMediaTypes.Contains(headerValue))
{
seenCompatibleMediaType = true;
break;
}
}
}
if (!seenCompatibleMediaType)
{
string allowedValues = string.Join(" or ", allowedMediaTypes.Select(value => $"'{value}'"));
await FlushResponseAsync(httpContext.Response, serializerOptions, new ErrorObject(HttpStatusCode.NotAcceptable)
{
Title = "The specified Accept header value does not contain any supported media types.",
Detail = $"Please include {allowedValues} in the Accept header values.",
Source = new ErrorSource
{
Header = "Accept"
}
});
return false;
}
return true;
}
private static async Task FlushResponseAsync(HttpResponse httpResponse, JsonSerializerOptions serializerOptions, ErrorObject error)
{
httpResponse.ContentType = HeaderConstants.MediaType;
httpResponse.StatusCode = (int)error.StatusCode;
var errorDocument = new Document
{
Errors = [error]
};
await JsonSerializer.SerializeAsync(httpResponse.Body, errorDocument, serializerOptions);
await httpResponse.Body.FlushAsync();
}
private static void SetupResourceRequest(JsonApiRequest request, ResourceType primaryResourceType, RouteValueDictionary routeValues,
HttpRequest httpRequest)
{
request.IsReadOnly = httpRequest.Method == HttpMethod.Get.Method || httpRequest.Method == HttpMethod.Head.Method;
request.PrimaryResourceType = primaryResourceType;
request.PrimaryId = GetPrimaryRequestId(routeValues);
string? relationshipName = GetRelationshipNameForSecondaryRequest(routeValues);
if (relationshipName != null)
{
request.Kind = IsRouteForRelationship(routeValues) ? EndpointKind.Relationship : EndpointKind.Secondary;
// @formatter:wrap_chained_method_calls chop_always
// @formatter:keep_existing_linebreaks true
request.WriteOperation =
httpRequest.Method == HttpMethod.Post.Method ? WriteOperationKind.AddToRelationship :
httpRequest.Method == HttpMethod.Patch.Method ? WriteOperationKind.SetRelationship :
httpRequest.Method == HttpMethod.Delete.Method ? WriteOperationKind.RemoveFromRelationship : null;
// @formatter:keep_existing_linebreaks restore
// @formatter:wrap_chained_method_calls restore
RelationshipAttribute? requestRelationship = primaryResourceType.FindRelationshipByPublicName(relationshipName);
if (requestRelationship != null)
{
request.Relationship = requestRelationship;
request.SecondaryResourceType = requestRelationship.RightType;
}
}
else
{
request.Kind = EndpointKind.Primary;
// @formatter:wrap_chained_method_calls chop_always
// @formatter:keep_existing_linebreaks true
request.WriteOperation =
httpRequest.Method == HttpMethod.Post.Method ? WriteOperationKind.CreateResource :
httpRequest.Method == HttpMethod.Patch.Method ? WriteOperationKind.UpdateResource :
httpRequest.Method == HttpMethod.Delete.Method ? WriteOperationKind.DeleteResource : null;
// @formatter:keep_existing_linebreaks restore
// @formatter:wrap_chained_method_calls restore
}
bool isGetAll = request.PrimaryId == null && request.IsReadOnly;
request.IsCollection = isGetAll || request.Relationship is HasManyAttribute;
}
private static string? GetPrimaryRequestId(RouteValueDictionary routeValues)
{
return routeValues.TryGetValue("id", out object? id) ? (string?)id : null;
}
private static string? GetRelationshipNameForSecondaryRequest(RouteValueDictionary routeValues)
{
return routeValues.TryGetValue("relationshipName", out object? routeValue) ? (string?)routeValue : null;
}
private static bool IsRouteForRelationship(RouteValueDictionary routeValues)
{
string actionName = (string)routeValues["action"]!;
return actionName.EndsWith("Relationship", StringComparison.Ordinal);
}
private static bool IsRouteForOperations(RouteValueDictionary routeValues)
{
string actionName = (string)routeValues["action"]!;
return actionName == "PostOperations";
}
private static void SetupOperationsRequest(JsonApiRequest request)
{
request.IsReadOnly = false;
request.Kind = EndpointKind.AtomicOperations;
}
}