|
| 1 | +using System.Net; |
| 2 | +using JsonApiDotNetCore.Configuration; |
| 3 | +using JsonApiDotNetCore.Errors; |
| 4 | +using JsonApiDotNetCore.Serialization.Objects; |
| 5 | +using Microsoft.AspNetCore.Http; |
| 6 | +using Microsoft.AspNetCore.Routing; |
| 7 | + |
| 8 | +namespace JsonApiDotNetCore.Middleware; |
| 9 | + |
| 10 | +/// <inheritdoc /> |
| 11 | +public class JsonApiContentNegotiator : IJsonApiContentNegotiator |
| 12 | +{ |
| 13 | + private readonly IJsonApiOptions _options; |
| 14 | + private readonly IHttpContextAccessor _httpContextAccessor; |
| 15 | + |
| 16 | + private HttpContext HttpContext |
| 17 | + { |
| 18 | + get |
| 19 | + { |
| 20 | + if (_httpContextAccessor.HttpContext == null) |
| 21 | + { |
| 22 | + throw new InvalidOperationException("An active HTTP request is required."); |
| 23 | + } |
| 24 | + |
| 25 | + return _httpContextAccessor.HttpContext; |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + public JsonApiContentNegotiator(IJsonApiOptions options, IHttpContextAccessor httpContextAccessor) |
| 30 | + { |
| 31 | + ArgumentGuard.NotNull(options); |
| 32 | + ArgumentGuard.NotNull(httpContextAccessor); |
| 33 | + |
| 34 | + _options = options; |
| 35 | + _httpContextAccessor = httpContextAccessor; |
| 36 | + } |
| 37 | + |
| 38 | + /// <inheritdoc /> |
| 39 | + public IReadOnlySet<JsonApiExtension> Negotiate() |
| 40 | + { |
| 41 | + IReadOnlyList<JsonApiMediaType> possibleMediaTypes = GetPossibleMediaTypes(); |
| 42 | + |
| 43 | + JsonApiMediaType? requestMediaType = ValidateContentType(possibleMediaTypes); |
| 44 | + return ValidateAcceptHeader(possibleMediaTypes, requestMediaType); |
| 45 | + } |
| 46 | + |
| 47 | + private JsonApiMediaType? ValidateContentType(IReadOnlyList<JsonApiMediaType> possibleMediaTypes) |
| 48 | + { |
| 49 | + if (HttpContext.Request.ContentType == null) |
| 50 | + { |
| 51 | + if (HttpContext.Request.ContentLength > 0) |
| 52 | + { |
| 53 | + throw CreateContentTypeError(possibleMediaTypes); |
| 54 | + } |
| 55 | + |
| 56 | + return null; |
| 57 | + } |
| 58 | + |
| 59 | + JsonApiMediaType? mediaType = JsonApiMediaType.TryParseContentTypeHeaderValue(HttpContext.Request.ContentType); |
| 60 | + |
| 61 | + if (mediaType == null || !possibleMediaTypes.Contains(mediaType)) |
| 62 | + { |
| 63 | + throw CreateContentTypeError(possibleMediaTypes); |
| 64 | + } |
| 65 | + |
| 66 | + return mediaType; |
| 67 | + } |
| 68 | + |
| 69 | + private IReadOnlySet<JsonApiExtension> ValidateAcceptHeader(IReadOnlyList<JsonApiMediaType> possibleMediaTypes, JsonApiMediaType? requestMediaType) |
| 70 | + { |
| 71 | + string[] acceptHeaderValues = HttpContext.Request.Headers.GetCommaSeparatedValues("Accept"); |
| 72 | + JsonApiMediaType? bestMatch = null; |
| 73 | + |
| 74 | + if (acceptHeaderValues.Length == 0 && possibleMediaTypes.Contains(JsonApiMediaType.Default)) |
| 75 | + { |
| 76 | + bestMatch = JsonApiMediaType.Default; |
| 77 | + } |
| 78 | + else |
| 79 | + { |
| 80 | + decimal bestQualityFactor = 0m; |
| 81 | + |
| 82 | + foreach (string acceptHeaderValue in acceptHeaderValues) |
| 83 | + { |
| 84 | + (JsonApiMediaType MediaType, decimal QualityFactor)? result = JsonApiMediaType.TryParseAcceptHeaderValue(acceptHeaderValue); |
| 85 | + |
| 86 | + if (result != null) |
| 87 | + { |
| 88 | + if (result.Value.MediaType.Equals(requestMediaType) && possibleMediaTypes.Contains(requestMediaType)) |
| 89 | + { |
| 90 | + // Content-Type always wins over other candidates, because JsonApiDotNetCore doesn't support |
| 91 | + // different extension sets for the request and response body. |
| 92 | + bestMatch = requestMediaType; |
| 93 | + break; |
| 94 | + } |
| 95 | + |
| 96 | + bool isBetterMatch = false; |
| 97 | + int? currentIndex = null; |
| 98 | + |
| 99 | + if (bestMatch == null) |
| 100 | + { |
| 101 | + isBetterMatch = true; |
| 102 | + } |
| 103 | + else if (result.Value.QualityFactor > bestQualityFactor) |
| 104 | + { |
| 105 | + isBetterMatch = true; |
| 106 | + } |
| 107 | + else if (result.Value.QualityFactor == bestQualityFactor) |
| 108 | + { |
| 109 | + if (result.Value.MediaType.Extensions.Count > bestMatch.Extensions.Count) |
| 110 | + { |
| 111 | + isBetterMatch = true; |
| 112 | + } |
| 113 | + else if (result.Value.MediaType.Extensions.Count == bestMatch.Extensions.Count) |
| 114 | + { |
| 115 | + int bestIndex = possibleMediaTypes.FindIndex(bestMatch); |
| 116 | + currentIndex = possibleMediaTypes.FindIndex(result.Value.MediaType); |
| 117 | + |
| 118 | + if (currentIndex != -1 && currentIndex < bestIndex) |
| 119 | + { |
| 120 | + isBetterMatch = true; |
| 121 | + } |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + if (isBetterMatch) |
| 126 | + { |
| 127 | + bool existsInPossibleMediaTypes = currentIndex >= 0 || possibleMediaTypes.Contains(result.Value.MediaType); |
| 128 | + |
| 129 | + if (existsInPossibleMediaTypes) |
| 130 | + { |
| 131 | + bestMatch = result.Value.MediaType; |
| 132 | + bestQualityFactor = result.Value.QualityFactor; |
| 133 | + } |
| 134 | + } |
| 135 | + } |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + if (bestMatch == null) |
| 140 | + { |
| 141 | + throw CreateAcceptHeaderError(possibleMediaTypes); |
| 142 | + } |
| 143 | + |
| 144 | + if (requestMediaType != null && !bestMatch.Equals(requestMediaType)) |
| 145 | + { |
| 146 | + throw CreateAcceptHeaderError(possibleMediaTypes); |
| 147 | + } |
| 148 | + |
| 149 | + return bestMatch.Extensions; |
| 150 | + } |
| 151 | + |
| 152 | + /// <summary> |
| 153 | + /// Gets the list of possible combinations of JSON:API extensions that are available at the current endpoint. The set of extensions in the request body |
| 154 | + /// must always be the same as in the response body. |
| 155 | + /// </summary> |
| 156 | + /// <remarks> |
| 157 | + /// Override this method to add support for custom JSON:API extensions. Implementations should take <see cref="IJsonApiOptions.Extensions" /> into |
| 158 | + /// account. During content negotiation, the first compatible entry with the highest number of extensions is preferred, but beware that clients can |
| 159 | + /// overrule this using quality factors in an Accept header. |
| 160 | + /// </remarks> |
| 161 | + protected virtual IReadOnlyList<JsonApiMediaType> GetPossibleMediaTypes() |
| 162 | + { |
| 163 | + List<JsonApiMediaType> mediaTypes = []; |
| 164 | + |
| 165 | + // Relaxed entries come after JSON:API compliant entries, which makes them less likely to be selected. |
| 166 | + |
| 167 | + if (IsOperationsEndpoint()) |
| 168 | + { |
| 169 | + if (_options.Extensions.Contains(JsonApiExtension.AtomicOperations)) |
| 170 | + { |
| 171 | + mediaTypes.Add(JsonApiMediaType.AtomicOperations); |
| 172 | + } |
| 173 | + |
| 174 | + if (_options.Extensions.Contains(JsonApiExtension.RelaxedAtomicOperations)) |
| 175 | + { |
| 176 | + mediaTypes.Add(JsonApiMediaType.RelaxedAtomicOperations); |
| 177 | + } |
| 178 | + } |
| 179 | + else |
| 180 | + { |
| 181 | + mediaTypes.Add(JsonApiMediaType.Default); |
| 182 | + } |
| 183 | + |
| 184 | + return mediaTypes.AsReadOnly(); |
| 185 | + } |
| 186 | + |
| 187 | + protected bool IsOperationsEndpoint() |
| 188 | + { |
| 189 | + RouteValueDictionary routeValues = HttpContext.GetRouteData().Values; |
| 190 | + return JsonApiMiddleware.IsRouteForOperations(routeValues); |
| 191 | + } |
| 192 | + |
| 193 | + private JsonApiException CreateContentTypeError(IReadOnlyList<JsonApiMediaType> possibleMediaTypes) |
| 194 | + { |
| 195 | + string allowedValues = string.Join(" or ", possibleMediaTypes.Select(mediaType => $"'{mediaType}'")); |
| 196 | + |
| 197 | + return new JsonApiException(new ErrorObject(HttpStatusCode.UnsupportedMediaType) |
| 198 | + { |
| 199 | + Title = "The specified Content-Type header value is not supported.", |
| 200 | + Detail = $"Use {allowedValues} instead of '{HttpContext.Request.ContentType}' for the Content-Type header value.", |
| 201 | + Source = new ErrorSource |
| 202 | + { |
| 203 | + Header = "Content-Type" |
| 204 | + } |
| 205 | + }); |
| 206 | + } |
| 207 | + |
| 208 | + private static JsonApiException CreateAcceptHeaderError(IReadOnlyList<JsonApiMediaType> possibleMediaTypes) |
| 209 | + { |
| 210 | + string allowedValues = string.Join(" or ", possibleMediaTypes.Select(mediaType => $"'{mediaType}'")); |
| 211 | + |
| 212 | + return new JsonApiException(new ErrorObject(HttpStatusCode.NotAcceptable) |
| 213 | + { |
| 214 | + Title = "The specified Accept header value does not contain any supported media types.", |
| 215 | + Detail = $"Include {allowedValues} in the Accept header values.", |
| 216 | + Source = new ErrorSource |
| 217 | + { |
| 218 | + Header = "Accept" |
| 219 | + } |
| 220 | + }); |
| 221 | + } |
| 222 | +} |
0 commit comments