Skip to content

Commit 980a67d

Browse files
authored
Enable override of chosen media type when Accept header is missing (used to workaround NSwag bug in OpenAPI) (#1644)
1 parent 0c79d35 commit 980a67d

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

src/JsonApiDotNetCore/Middleware/JsonApiContentNegotiator.cs

+21-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System.Net;
2+
using JetBrains.Annotations;
23
using JsonApiDotNetCore.Configuration;
34
using JsonApiDotNetCore.Errors;
45
using JsonApiDotNetCore.Serialization.Objects;
@@ -8,6 +9,7 @@
89
namespace JsonApiDotNetCore.Middleware;
910

1011
/// <inheritdoc />
12+
[PublicAPI]
1113
public class JsonApiContentNegotiator : IJsonApiContentNegotiator
1214
{
1315
private readonly IJsonApiOptions _options;
@@ -71,9 +73,9 @@ private IReadOnlySet<JsonApiMediaTypeExtension> ValidateAcceptHeader(IReadOnlyLi
7173
string[] acceptHeaderValues = HttpContext.Request.Headers.GetCommaSeparatedValues("Accept");
7274
JsonApiMediaType? bestMatch = null;
7375

74-
if (acceptHeaderValues.Length == 0 && possibleMediaTypes.Contains(JsonApiMediaType.Default))
76+
if (acceptHeaderValues.Length == 0)
7577
{
76-
bestMatch = JsonApiMediaType.Default;
78+
bestMatch = GetDefaultMediaType(possibleMediaTypes, requestMediaType);
7779
}
7880
else
7981
{
@@ -149,6 +151,23 @@ private IReadOnlySet<JsonApiMediaTypeExtension> ValidateAcceptHeader(IReadOnlyLi
149151
return bestMatch.Extensions;
150152
}
151153

154+
/// <summary>
155+
/// Returns the JSON:API media type (possibly including extensions) to use when no Accept header was sent.
156+
/// </summary>
157+
/// <param name="possibleMediaTypes">
158+
/// The media types returned from <see cref="GetPossibleMediaTypes" />.
159+
/// </param>
160+
/// <param name="requestMediaType">
161+
/// The media type from in the Content-Type header.
162+
/// </param>
163+
/// <returns>
164+
/// The default media type to use, or <c>null</c> if not available.
165+
/// </returns>
166+
protected virtual JsonApiMediaType? GetDefaultMediaType(IReadOnlyList<JsonApiMediaType> possibleMediaTypes, JsonApiMediaType? requestMediaType)
167+
{
168+
return possibleMediaTypes.Contains(JsonApiMediaType.Default) ? JsonApiMediaType.Default : null;
169+
}
170+
152171
/// <summary>
153172
/// 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
154173
/// must always be the same as in the response body.

0 commit comments

Comments
 (0)