Skip to content

Support processing XML comments on [AsParameters] parameter #63166

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
69 changes: 69 additions & 0 deletions src/OpenApi/gen/XmlCommentGenerator.Emitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ namespace Microsoft.AspNetCore.OpenApi.Generated
using System.Threading.Tasks;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi;

Expand Down Expand Up @@ -152,6 +153,30 @@ public static string CreateDocumentationId(this PropertyInfo property)
return sb.ToString();
}

/// <summary>
/// Generates a documentation comment ID for a property given its container type and property name.
/// Example: P:Namespace.ContainingType.PropertyName
/// </summary>
public static string CreateDocumentationId(Type containerType, string propertyName)
{
if (containerType == null)
{
throw new ArgumentNullException(nameof(containerType));
}
if (string.IsNullOrEmpty(propertyName))
{
throw new ArgumentException("Property name cannot be null or empty.", nameof(propertyName));
}

var sb = new StringBuilder();
sb.Append("P:");
sb.Append(GetTypeDocId(containerType, includeGenericArguments: false, omitGenericArity: false));
sb.Append('.');
sb.Append(propertyName);

return sb.ToString();
}

/// <summary>
/// Generates a documentation comment ID for a method (or constructor).
/// For example:
Expand Down Expand Up @@ -416,6 +441,50 @@ public Task TransformAsync(OpenApiOperation operation, OpenApiOperationTransform
}
}
}
foreach (var parameterDescription in context.Description.ParameterDescriptions)
{
var metadata = parameterDescription.ModelMetadata;
if (metadata.MetadataKind == ModelMetadataKind.Property
&& metadata.ContainerType is { } containerType
&& metadata.PropertyName is { } propertyName)
{
var propertyDocId = DocumentationCommentIdHelper.CreateDocumentationId(containerType, propertyName!);
if (XmlCommentCache.Cache.TryGetValue(DocumentationCommentIdHelper.NormalizeDocId(propertyDocId), out var propertyComment))
{
var parameter = operation.Parameters?.SingleOrDefault(p => p.Name == metadata.Name);
if (parameter is null)
{
if (operation.RequestBody is not null)
{
operation.RequestBody.Description = propertyComment.Value ?? propertyComment.Returns ?? propertyComment.Summary;
if (propertyComment.Examples?.FirstOrDefault() is { } jsonString)
{
var content = operation.RequestBody.Content?.Values;
var parsedExample = jsonString.Parse();
if (content is null)
{
continue;
}
foreach (var mediaType in content)
{
mediaType.Example = parsedExample;
}
}
}
continue;
}
var targetOperationParameter = UnwrapOpenApiParameter(parameter);
if (targetOperationParameter is not null)
{
targetOperationParameter.Description = propertyComment.Value ?? propertyComment.Returns ?? propertyComment.Summary;
if (propertyComment.Examples?.FirstOrDefault() is { } jsonString)
{
targetOperationParameter.Example = jsonString.Parse();
}
}
}
}
}

return Task.CompletedTask;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public async Task SupportsXmlCommentsOnOperationsFromMinimalApis()
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder();

Expand All @@ -44,6 +45,10 @@ public async Task SupportsXmlCommentsOnOperationsFromMinimalApis()
app.MapGet("/15", RouteHandlerExtensionMethods.Get15);
app.MapPost("/16", RouteHandlerExtensionMethods.Post16);
app.MapGet("/17", RouteHandlerExtensionMethods.Get17);
app.MapPost("/18", RouteHandlerExtensionMethods.Post18);
app.MapPost("/19", RouteHandlerExtensionMethods.Post19);
app.MapGet("/20", RouteHandlerExtensionMethods.Get20);
app.MapGet("/21", RouteHandlerExtensionMethods.Get21);

app.Run();

Expand Down Expand Up @@ -207,10 +212,81 @@ public static void Post16(Example example)
public static int[][] Get17(int[] args)
{
return [[1, 2, 3], [4, 5, 6], [7, 8, 9], args];
}

/// <summary>
/// A summary of Post18.
/// </summary>
public static int Post18([AsParameters] FirstParameters queryParameters, [AsParameters] SecondParameters bodyParameters)
{
return 0;
}

/// <summary>
/// Tests mixed regular and AsParameters with examples.
/// </summary>
/// <param name="regularParam">A regular parameter with documentation.</param>
/// <param name="mixedParams">Mixed parameter class with various types.</param>
public static IResult Post19(string regularParam, [AsParameters] MixedParametersClass mixedParams)
{
return TypedResults.Ok($"Regular: {regularParam}, Email: {mixedParams.Email}");
}

/// <summary>
/// Tests AsParameters with different binding sources.
/// </summary>
/// <param name="bindingParams">Parameters from different sources.</param>
public static IResult Get20([AsParameters] BindingSourceParametersClass bindingParams)
{
return TypedResults.Ok($"Query: {bindingParams.QueryParam}, Header: {bindingParams.HeaderParam}");
}

/// <summary>
/// Tests XML documentation priority order (value > returns > summary).
/// </summary>
/// <param name="priorityParams">Parameters demonstrating XML doc priority.</param>
public static IResult Get21([AsParameters] XmlDocPriorityParametersClass priorityParams)
{
return TypedResults.Ok($"Processed parameters");
}
}

public class FirstParameters
{
/// <summary>
/// The name of the person.
/// </summary>
public string? Name { get; set; }
/// <summary>
/// The age of the person.
/// </summary>
/// <example>30</example>
public int? Age { get; set; }
/// <summary>
/// The user information.
/// </summary>
/// <example>
/// {
/// "username": "johndoe",
/// "email": "[email protected]"
/// }
/// </example>
public User? User { get; set; }
}

public class SecondParameters
{
/// <summary>
/// The description of the project.
/// </summary>
public string? Description { get; set; }
/// <summary>
/// The service used for testing.
/// </summary>
[FromServices]
public Example Service { get; set; }
}

public class User
{
public string Username { get; set; } = string.Empty;
Expand All @@ -232,6 +308,69 @@ public Example(Func<object?, int> function, object? state) : base(function, stat
{
}
}

public class MixedParametersClass
{
/// <summary>
/// The user's email address.
/// </summary>
/// <example>"[email protected]"</example>
public string? Email { get; set; }

/// <summary>
/// The user's age in years.
/// </summary>
/// <example>25</example>
public int Age { get; set; }

/// <summary>
/// Whether the user is active.
/// </summary>
/// <example>true</example>
public bool IsActive { get; set; }
}

public class BindingSourceParametersClass
{
/// <summary>
/// Query parameter from URL.
/// </summary>
[FromQuery]
public string? QueryParam { get; set; }

/// <summary>
/// Header value from request.
/// </summary>
[FromHeader]
public string? HeaderParam { get; set; }
}

public class XmlDocPriorityParametersClass
{
/// <summary>
/// Property with only summary documentation.
/// </summary>
public string? SummaryOnlyProperty { get; set; }

/// <summary>
/// Property with summary documentation that should be overridden.
/// </summary>
/// <returns>Returns-based description that should take precedence over summary.</returns>
public string? SummaryAndReturnsProperty { get; set; }

/// <summary>
/// Property with all three types of documentation.
/// </summary>
/// <returns>Returns-based description that should be overridden by value.</returns>
/// <value>Value-based description that should take highest precedence.</value>
public string? AllThreeProperty { get; set; }

/// <returns>Returns-only description.</returns>
public string? ReturnsOnlyProperty { get; set; }

/// <value>Value-only description.</value>
public string? ValueOnlyProperty { get; set; }
}
""";
var generator = new XmlCommentGenerator();
await SnapshotTestHelper.Verify(source, generator, out var compilation);
Expand Down Expand Up @@ -304,6 +443,51 @@ await SnapshotTestHelper.VerifyOpenApi(compilation, document =>

var path17 = document.Paths["/17"].Operations[HttpMethod.Get];
Assert.Equal("A summary of Get17.", path17.Summary);

var path18 = document.Paths["/18"].Operations[HttpMethod.Post];
Assert.Equal("A summary of Post18.", path18.Summary);
Assert.Equal("The name of the person.", path18.Parameters[0].Description);
Assert.Equal("The age of the person.", path18.Parameters[1].Description);
Assert.Equal(30, path18.Parameters[1].Example.GetValue<int>());
Assert.Equal("The description of the project.", path18.Parameters[2].Description);
Assert.Equal("The user information.", path18.RequestBody.Description);
var path18RequestBody = path18.RequestBody.Content["application/json"];
var path18Example = Assert.IsAssignableFrom<JsonNode>(path18RequestBody.Example);
Assert.Equal("johndoe", path18Example["username"].GetValue<string>());
Assert.Equal("[email protected]", path18Example["email"].GetValue<string>());

var path19 = document.Paths["/19"].Operations[HttpMethod.Post];
Assert.Equal("Tests mixed regular and AsParameters with examples.", path19.Summary);
Assert.Equal("A regular parameter with documentation.", path19.Parameters[0].Description);
Assert.Equal("The user's email address.", path19.Parameters[1].Description);
Assert.Equal("[email protected]", path19.Parameters[1].Example.GetValue<string>());
Assert.Equal("The user's age in years.", path19.Parameters[2].Description);
Assert.Equal(25, path19.Parameters[2].Example.GetValue<int>());
Assert.Equal("Whether the user is active.", path19.Parameters[3].Description);
Assert.True(path19.Parameters[3].Example.GetValue<bool>());

var path20 = document.Paths["/20"].Operations[HttpMethod.Get];
Assert.Equal("Tests AsParameters with different binding sources.", path20.Summary);
Assert.Equal("Query parameter from URL.", path20.Parameters[0].Description);
Assert.Equal("Header value from request.", path20.Parameters[1].Description);

// Test XML documentation priority order: value > returns > summary
var path22 = document.Paths["/21"].Operations[HttpMethod.Get];
// Find parameters by name for clearer assertions
var summaryOnlyParam = path22.Parameters.First(p => p.Name == "SummaryOnlyProperty");
Assert.Equal("Property with only summary documentation.", summaryOnlyParam.Description);

var summaryAndReturnsParam = path22.Parameters.First(p => p.Name == "SummaryAndReturnsProperty");
Assert.Equal("Returns-based description that should take precedence over summary.", summaryAndReturnsParam.Description);

var allThreeParam = path22.Parameters.First(p => p.Name == "AllThreeProperty");
Assert.Equal("Value-based description that should take highest precedence.", allThreeParam.Description);

var returnsOnlyParam = path22.Parameters.First(p => p.Name == "ReturnsOnlyProperty");
Assert.Equal("Returns-only description.", returnsOnlyParam.Description);

var valueOnlyParam = path22.Parameters.First(p => p.Name == "ValueOnlyProperty");
Assert.Equal("Value-only description.", valueOnlyParam.Description);
});
}
}
Loading
Loading