Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/workflows/cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ jobs:
matrix:
os: [ubuntu-latest]
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v6
- name: Setup .NET
id: dotnet
uses: actions/setup-dotnet@v4
uses: actions/setup-dotnet@v5
with:
dotnet-version: ${{ env.dotnet_version }}
- name: Build
Expand All @@ -40,7 +40,7 @@ jobs:

release:
name: Create Release
uses: Fresa/Library.Net.ContinuousDelivery/.github/workflows/release.yml@v0
uses: Fresa/Library.Net.ContinuousDelivery/.github/workflows/release.yml@v1
needs: test
if: github.repository == needs.test.outputs.repository && github.actor != 'dependabot[bot]'
permissions:
Expand Down
8 changes: 5 additions & 3 deletions .github/workflows/lint-openapi.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@ jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6

- name: Install vacuum
run: curl -fsSL https://quobix.com/scripts/install_vacuum.sh | sh
run: curl -fsSL https://quobix.com/scripts/install_vacuum.sh | VERSION=0.29.1 sh

- name: Lint OpenAPI specs
run: vacuum lint tests/{*/,*/*/}openapi*.{json,yaml}
run: |
shopt -s nullglob
vacuum lint tests/{*/,*/*/}openapi*.{json,yaml}
14 changes: 8 additions & 6 deletions src/OpenAPI.WebApiGenerator/ApiGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -169,12 +169,14 @@ private static void GenerateCode(SourceProductionContext context,
response.Content?.Where(responseContent =>
openApiResponseVisitor.HasContent(responseContent.Value)) ?? [];
var responseBodyGenerators = responseContent.Select(mediaContent =>
{
var contentMediaType = mediaContent.Value;
var contentSchemaReference = openApiResponseVisitor.GetSchemaReference(contentMediaType);
var typeDeclaration = schemaGenerator.Generate(contentSchemaReference);
return new ResponseBodyContentGenerator(mediaContent, typeDeclaration);
}).ToList();
{
var contentMediaType = mediaContent.Value;
var contentSchemaReference = openApiResponseVisitor.GetSchemaReference(contentMediaType);
var typeDeclaration = schemaGenerator.Generate(contentSchemaReference);
return new ResponseBodyContentGenerator(mediaContent, typeDeclaration);
})
.OrderByDescending(generator => generator.ContentType.GetPrecedence())
.ToList();

var responseHeaderGenerators = response.Headers?.Select(valuePair =>
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,9 +168,10 @@ private static bool TryParse<T>(StringValues values, IParameter parameter, [NotN
}

var parser = GetParser(parameter);
var stringValue = parser.ValueIncludesParameterName
? string.Join('&', values.Select(value => $"{parameter.Name}={value}"))
: values.Single();
var stringValue = string.Join(parser.Delimiter,
parser.ValueIncludesParameterName
? values.Select(value => $"{parameter.Name}={value}")
: values);

value = Parse<T>(parser, stringValue);
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,24 @@ internal sealed class ResponseBodyContentGenerator
{
private readonly string _contentVariableName;
internal string ClassName { get; }
private readonly MediaTypeHeaderValue _contentType;
internal MediaTypeHeaderValue ContentType { get; }
private readonly TypeDeclaration _typeDeclaration;
private readonly bool _isContentTypeRange;
private readonly bool _isSequentialMediaType;

public ResponseBodyContentGenerator(KeyValuePair<string, IOpenApiMediaType> contentMediaType, TypeDeclaration typeDeclaration)
{
_contentType = MediaTypeHeaderValue.Parse(contentMediaType.Key);
ContentType = MediaTypeHeaderValue.Parse(contentMediaType.Key);
_typeDeclaration = typeDeclaration;
_isSequentialMediaType = contentMediaType.Value.ItemSchema != null;
_isContentTypeRange = _contentType.MediaType.EndsWith("*");
_contentVariableName = _contentType.MediaType switch
_isContentTypeRange = ContentType.MediaType.EndsWith("*");
_contentVariableName = ContentType.MediaType switch
{
"*/*" => "any",
not null when _isContentTypeRange =>
$"any{_contentType.MediaType.TrimEnd('*').TrimEnd('/').ToLower().ToPascalCase()}",
$"any{ContentType.MediaType.TrimEnd('*').TrimEnd('/').ToLower().ToPascalCase()}",
null => throw new InvalidOperationException("Content type is null"),
_ => _contentType.MediaType.ToLower().ToCamelCase()
_ => ContentType.MediaType.ToLower().ToCamelCase()
};

ClassName = _contentVariableName.ToPascalCase();
Expand All @@ -40,7 +40,7 @@ public string GenerateResponseClass(string responseClassName, string contentType
_isSequentialMediaType ?
$$"""
/// <summary>
/// Response for content {{_contentType}}
/// Response for content {{ContentType}}
/// </summary>
internal sealed class {{ClassName}} : {{responseClassName}}
{
Expand All @@ -51,12 +51,12 @@ internal sealed class {{ClassName}} : {{responseClassName}}
private readonly WebApiConfiguration _configuration;

/// <summary>
/// Construct response for content {{_contentType}}
/// Construct response for content {{ContentType}}
/// </summary>
/// <param name="request">Request</param>{{(_isContentTypeRange ?
$"""

/// <param name="contentType">Content type must match range {_contentType.MediaType}</param>
/// <param name="contentType">Content type must match range {ContentType.MediaType}</param>
""" : "")}}
public {{ClassName}}(Request request{{(_isContentTypeRange ? ", string contentType" : "")}})
{{{(_isContentTypeRange ?
Expand All @@ -68,7 +68,7 @@ internal sealed class {{ClassName}} : {{responseClassName}}
_content = new(request.HttpContext.Response.BodyWriter);
_operation = request.HttpContext.RequestServices.GetRequiredService<Operation>();
_configuration = request.HttpContext.RequestServices.GetRequiredService<WebApiConfiguration>();
{{contentTypeFieldName}} = {{(_isContentTypeRange ? "contentType" : $"\"{_contentType.MediaType}\"")}};
{{contentTypeFieldName}} = {{(_isContentTypeRange ? "contentType" : $"\"{ContentType.MediaType}\"")}};
}

/// <summary>
Expand All @@ -85,7 +85,7 @@ internal void WriteItem({{_typeDeclaration.FullyQualifiedDotnetTypeName()}} item
_currentItem = null;
}

internal static ContentMediaType<{{responseClassName}}> ContentMediaType { get; } = new(MediaTypeHeaderValue.Parse("{{_contentType}}"));
internal static ContentMediaType<{{responseClassName}}> ContentMediaType { get; } = new(MediaTypeHeaderValue.Parse("{{ContentType}}"));
/// <inheritdoc/>
internal override void WriteTo(HttpResponse httpResponse)
{
Expand Down Expand Up @@ -127,19 +127,19 @@ _currentItem is null

$$"""
/// <summary>
/// Response for content {{_contentType}}
/// Response for content {{ContentType}}
/// </summary>
internal sealed class {{ClassName}} : {{responseClassName}}
{
private {{_typeDeclaration.FullyQualifiedDotnetTypeName()}} _content;

/// <summary>
/// Construct response for content {{_contentType}}
/// Construct response for content {{ContentType}}
/// </summary>
/// <param name="{{_contentVariableName}}">Content</param>{{(_isContentTypeRange ?
$"""

/// <param name="contentType">Content type must match range {_contentType.MediaType}</param>
/// <param name="contentType">Content type must match range {ContentType.MediaType}</param>
""" : "")}}
public {{ClassName}}({{_typeDeclaration.FullyQualifiedDotnetTypeName()}} {{_contentVariableName}}{{(_isContentTypeRange ? ", string contentType" : "")}})
{{{(_isContentTypeRange ?
Expand All @@ -148,10 +148,10 @@ internal sealed class {{ClassName}} : {{responseClassName}}
EnsureExpectedContentType(MediaTypeHeaderValue.Parse(contentType), ContentMediaType);
""" : "")}}
_content = {{_contentVariableName}};
{{contentTypeFieldName}} = {{(_isContentTypeRange ? "contentType" : $"\"{_contentType.MediaType}\"")}};
{{contentTypeFieldName}} = {{(_isContentTypeRange ? "contentType" : $"\"{ContentType.MediaType}\"")}};
}

internal static ContentMediaType<{{responseClassName}}> ContentMediaType { get; } = new(MediaTypeHeaderValue.Parse("{{_contentType}}"));
internal static ContentMediaType<{{responseClassName}}> ContentMediaType { get; } = new(MediaTypeHeaderValue.Parse("{{ContentType}}"));
/// <inheritdoc/>
internal override void WriteTo(HttpResponse httpResponse)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ internal sealed class ResponseContentGenerator
private readonly string _responseClassName;
private readonly string _responseStatusCodePattern;
private readonly IOpenApiResponse _response;
private readonly bool _hasExplicitStatusCode;
private readonly bool _hasDefaultStatusCode;

private ResponseContentGenerator(
KeyValuePair<string, IOpenApiResponse> response)
Expand All @@ -36,6 +38,10 @@ var chr when char.IsDigit(chr) => "X",
_responseStatusCodePattern = responseStatusCodePattern;
_responseClassName = responseClassName;
_response = response.Value;
_hasExplicitStatusCode = int.TryParse(_responseStatusCodePattern, out _);
_hasDefaultStatusCode = _responseStatusCodePattern == "default";
Precedence = _hasExplicitStatusCode ? 0 : _hasDefaultStatusCode ? 10 : 5;

}
public ResponseContentGenerator(
KeyValuePair<string, IOpenApiResponse> response,
Expand All @@ -46,6 +52,8 @@ public ResponseContentGenerator(
_headerGenerators = headerGenerators;
}

internal int Precedence { get; }

public string GenerateResponseContentClass()
{
var anyHeaders = _headerGenerators.Any();
Expand All @@ -55,9 +63,7 @@ public string GenerateResponseContentClass()
const string responseVariableName = "httpResponse";
const string contentTypeFieldName = "_contentType";

var hasExplicitStatusCode = int.TryParse(_responseStatusCodePattern, out _);
var hasDefaultStatusCode = _responseStatusCodePattern == "default";
var needsStatusCodeValidation = !hasExplicitStatusCode && !hasDefaultStatusCode;
var needsStatusCodeValidation = !_hasExplicitStatusCode && !_hasDefaultStatusCode;

return
$$$"""
Expand All @@ -79,13 +85,13 @@ public string GenerateResponseContentClass()
];
""" : "")}}}

private int _statusCode{{{(hasExplicitStatusCode ? $" = {_responseStatusCodePattern}" : string.Empty)}}};
private int _statusCode{{{(_hasExplicitStatusCode ? $" = {_responseStatusCodePattern}" : string.Empty)}}};
/// <summary>
/// Response status code
/// </summary>
internal int StatusCode
{
get => _statusCode;{{{(hasExplicitStatusCode ? "" :
get => _statusCode;{{{(_hasExplicitStatusCode ? "" :
$"""
init => _statusCode = {(needsStatusCodeValidation ? $"Validate{_responseStatusCodePattern.First()}xxStatusCode(value)" : "value")};
""")}}}
Expand Down
25 changes: 19 additions & 6 deletions src/OpenAPI.WebApiGenerator/CodeGeneration/ResponseGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,13 +123,26 @@ internal bool TryMatchAcceptMediaType<T>(
if ((acceptMediaType.Quality ?? 1.0) <= 0)
continue;

foreach (var mediaType in mediaTypes)
// Exact match
var match = mediaTypes.FirstOrDefault(mediaType =>
acceptMediaType.IsSubsetOf(mediaType.Value) &&
mediaType.Value.IsSubsetOf(acceptMediaType));

// Accept media type is broader than a supported media type;
// */*, application/*, application/*+json -> matches Accept header */*
if (match.Value is null)
match = mediaTypes.FirstOrDefault(mediaType =>
mediaType.Value.IsSubsetOf(acceptMediaType));

// Accept media type fits within a broader supported media type;
// Accept header application/json matches -> */*, application/*
if (match.Value is null)
match = mediaTypes.FirstOrDefault(mediaType =>
acceptMediaType.IsSubsetOf(mediaType.Value));

if (match.Value is not null)
{
if (!mediaType.Value.IsSubsetOf(acceptMediaType))
{
continue;
}
matchedContentMediaType = mediaType;
matchedContentMediaType = match;
return true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ internal static int GetPrecedence(this MediaTypeHeaderValue value) =>
{
"*/*" => 0,
not null when value.MediaType.EndsWith("*") => 100,
not null when value.MediaType.Contains("+") => 2000,
_ => 1000
};
}
2 changes: 1 addition & 1 deletion tests/Example.OpenApi20/Example.OpenApi20.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
<PackageReference Include="Corvus.Json.ExtendedTypes" Version="4.4.2" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.12" />
<PackageReference Include="Microsoft.DotNet.ApiCompat.Task" Version="10.0.202" PrivateAssets="all" IsImplicitlyDefined="true" />
<PackageReference Include="ParameterStyleParsers.OpenAPI" Version="1.4.0" />
<PackageReference Include="ParameterStyleParsers.OpenAPI" Version="1.5.0" />
</ItemGroup>

<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion tests/Example.OpenApi30/Example.OpenApi30.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
<PackageReference Include="Microsoft.DotNet.ApiCompat.Task" Version="10.0.202" PrivateAssets="all" IsImplicitlyDefined="true" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.12" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="9.0.12" />
<PackageReference Include="ParameterStyleParsers.OpenAPI" Version="1.4.0" />
<PackageReference Include="ParameterStyleParsers.OpenAPI" Version="1.5.0" />
</ItemGroup>

<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion tests/Example.OpenApi31/Example.OpenApi31.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
<PackageReference Include="Microsoft.AspNetCore.Authentication.Certificate" Version="9.0.12" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.12" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="9.0.12" />
<PackageReference Include="ParameterStyleParsers.OpenAPI" Version="1.4.0" />
<PackageReference Include="ParameterStyleParsers.OpenAPI" Version="1.5.0" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,36 @@ public async Task ExportingFooEvents_ShouldReturnOkWithSequentialJson(string med
JsonNode.Parse(lines[0]).GetValue<string>("#/Name").Should().Be("foo1");
JsonNode.Parse(lines[1]).GetValue<string>("#/Name").Should().Be("foo2");
}

[Theory]
// Media type ranges match any supported media type; the most specific one is preferred
[InlineData("*/*", "application/geo+json-seq")]
[InlineData("application/*", "application/geo+json-seq")]
// A specific accepted media type is preferred over a range with the same quality
[InlineData("application/*, application/x-ndjson", "application/x-ndjson")]
// Higher quality wins over declaration order
[InlineData("application/jsonl;q=0.5, application/x-ndjson", "application/x-ndjson")]
[InlineData("application/jsonl, application/x-ndjson;q=0.5", "application/jsonl")]
// q=0 means not acceptable
[InlineData("application/json-seq;q=0, application/x-ndjson;q=0.5", "application/x-ndjson")]
// An exactly supported media type is preferred over a suffixed specialization of it
[InlineData("application/json-seq", "application/json-seq")]
// A suffix media type range prefers the most specific supported media type
[InlineData("application/*+json-seq", "application/geo+json-seq")]
public async Task ExportingFooEvents_NegotiatingAcceptedMediaType_ShouldReturnBestMatch(
string acceptHeader, string expectedMediaType)
{
using var client = app.CreateClient();
var request = new HttpRequestMessage
{
RequestUri = new Uri(client.BaseAddress!, "/foo/1/events"),
Method = HttpMethod.Get
};
request.Headers.TryAddWithoutValidation("Accept", acceptHeader);

var result = await client.SendAsync(request, CancellationToken);

result.StatusCode.Should().Be(HttpStatusCode.OK);
result.Content.Headers.ContentType?.MediaType.Should().Be(expectedMediaType);
}
}
2 changes: 1 addition & 1 deletion tests/Example.OpenApi32/Example.OpenApi32.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
<PackageReference Include="Microsoft.AspNetCore.Authentication.Certificate" Version="9.0.12" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.12" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="9.0.12" />
<PackageReference Include="ParameterStyleParsers.OpenAPI" Version="1.4.0" />
<PackageReference Include="ParameterStyleParsers.OpenAPI" Version="1.5.0" />
</ItemGroup>

<ItemGroup>
Expand Down
4 changes: 2 additions & 2 deletions tests/Example.OpenApi32/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -137,12 +137,12 @@
"$ref": "#/components/schemas/FooProperties"
}
},
"application/json-seq": {
"application/geo+json-seq": {
"itemSchema": {
"$ref": "#/components/schemas/FooProperties"
}
},
"application/geo+json-seq": {
"application/json-seq": {
"itemSchema": {
"$ref": "#/components/schemas/FooProperties"
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public void ListOfRequestBodyContentGenerators_SortByContentType_SortsAccordingT
CreateGenerator("*/*"),
CreateGenerator("application/json; q=0.5"),
CreateGenerator("text/*"),
CreateGenerator("application/geo+json"),
CreateGenerator("application/json"),
CreateGenerator("text/*; q=0.9"),
CreateGenerator("application/json; charset=utf-8"),
Expand All @@ -28,6 +29,7 @@ public void ListOfRequestBodyContentGenerators_SortByContentType_SortsAccordingT
.ToArray();

sorted.Should().ContainInOrder(
"application/geo+json",
"application/json; charset=utf-8",
"application/json",
"text/plain",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ public void MediaTypeHeaderValue_MatchConditionExpressions(string mediaTypeValue
[InlineData("application/*; charset=utf-8; boundary=something", 102)]
[InlineData("application/*; charset=utf-8; boundary=something; foo=bar", 103)]
[InlineData("application/json", 1000)]
[InlineData("application/geo+json", 2000)]
[InlineData("application/json; charset=utf-8", 1001)]
[InlineData("application/json; charset=utf-8; boundary=something", 1002)]
[InlineData("multipart/form-data; boundary", 1001)]
Expand Down
Loading