Skip to content

Commit

Permalink
Enable override of chosen media type when Accept header is missing (u…
Browse files Browse the repository at this point in the history
…sed to workaround NSwag bug in OpenAPI) (#1644)
  • Loading branch information
bkoelman authored Nov 26, 2024
1 parent 0c79d35 commit 980a67d
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions src/JsonApiDotNetCore/Middleware/JsonApiContentNegotiator.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Net;
using JetBrains.Annotations;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Errors;
using JsonApiDotNetCore.Serialization.Objects;
Expand All @@ -8,6 +9,7 @@
namespace JsonApiDotNetCore.Middleware;

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

if (acceptHeaderValues.Length == 0 && possibleMediaTypes.Contains(JsonApiMediaType.Default))
if (acceptHeaderValues.Length == 0)
{
bestMatch = JsonApiMediaType.Default;
bestMatch = GetDefaultMediaType(possibleMediaTypes, requestMediaType);
}
else
{
Expand Down Expand Up @@ -149,6 +151,23 @@ private IReadOnlySet<JsonApiMediaTypeExtension> ValidateAcceptHeader(IReadOnlyLi
return bestMatch.Extensions;
}

/// <summary>
/// Returns the JSON:API media type (possibly including extensions) to use when no Accept header was sent.
/// </summary>
/// <param name="possibleMediaTypes">
/// The media types returned from <see cref="GetPossibleMediaTypes" />.
/// </param>
/// <param name="requestMediaType">
/// The media type from in the Content-Type header.
/// </param>
/// <returns>
/// The default media type to use, or <c>null</c> if not available.
/// </returns>
protected virtual JsonApiMediaType? GetDefaultMediaType(IReadOnlyList<JsonApiMediaType> possibleMediaTypes, JsonApiMediaType? requestMediaType)
{
return possibleMediaTypes.Contains(JsonApiMediaType.Default) ? JsonApiMediaType.Default : null;
}

/// <summary>
/// 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
/// must always be the same as in the response body.
Expand Down

0 comments on commit 980a67d

Please sign in to comment.