Skip to content
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

Fixed the issue #60096

Merged
merged 7 commits into from
Feb 4, 2025
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
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Metadata;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.Filters;
Expand Down Expand Up @@ -349,9 +350,41 @@ internal PropertyModel CreatePropertyModel(PropertyInfo propertyInfo)
applicableAttributes.AddRange(routeAttributes);
AddRange(actionModel.Selectors, CreateSelectors(applicableAttributes));

AddReturnTypeMetadata(actionModel.Selectors, methodInfo);

return actionModel;
}

internal static void AddReturnTypeMetadata(IList<SelectorModel> selectors, MethodInfo methodInfo)
{
// Get metadata from return type
var returnType = methodInfo.ReturnType;
if (CoercedAwaitableInfo.IsTypeAwaitable(returnType, out var coercedAwaitableInfo))
{
returnType = coercedAwaitableInfo.AwaitableInfo.ResultType;
}

if (returnType is not null && typeof(IEndpointMetadataProvider).IsAssignableFrom(returnType))
{
// Return type implements IEndpointMetadataProvider
var builder = new InertEndpointBuilder();
var invokeArgs = new object[2];
invokeArgs[0] = methodInfo;
invokeArgs[1] = builder;
EndpointMetadataPopulator.PopulateMetadataForEndpointMethod.MakeGenericMethod(returnType).Invoke(null, invokeArgs);

// The metadata is added to the builder's metadata collection.
// We need to populate the selectors with that metadata.
foreach (var metadata in builder.Metadata)
{
foreach (var selector in selectors)
{
selector.EndpointMetadata.Add(metadata);
}
}
}
}

private string CanonicalizeActionName(string actionName)
{
const string Suffix = "Async";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@
<property name="Scope">member</property>
<property name="Target">M:Microsoft.AspNetCore.Mvc.AcceptedAtRouteResult.#ctor(System.String,System.Object,System.Object)</property>
</attribute>
<attribute fullname="System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute">
<argument>ILLink</argument>
<argument>IL2026</argument>
<property name="Scope">member</property>
<property name="Target">M:Microsoft.AspNetCore.Mvc.ApplicationModels.DefaultApplicationModelProvider.AddReturnTypeMetadata(System.Collections.Generic.IList{Microsoft.AspNetCore.Mvc.ApplicationModels.SelectorModel},System.Reflection.MethodInfo)</property>
</attribute>
<attribute fullname="System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute">
<argument>ILLink</argument>
<argument>IL2026</argument>
Expand Down Expand Up @@ -517,6 +523,12 @@
<property name="Scope">member</property>
<property name="Target">M:Microsoft.AspNetCore.Mvc.ApplicationParts.ProvideApplicationPartFactoryAttribute.GetFactoryType</property>
</attribute>
<attribute fullname="System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute">
<argument>ILLink</argument>
<argument>IL2060</argument>
<property name="Scope">member</property>
<property name="Target">M:Microsoft.AspNetCore.Mvc.ApplicationModels.DefaultApplicationModelProvider.AddReturnTypeMetadata(System.Collections.Generic.IList{Microsoft.AspNetCore.Mvc.ApplicationModels.SelectorModel},System.Reflection.MethodInfo)</property>
</attribute>
<attribute fullname="System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute">
<argument>ILLink</argument>
<argument>IL2060</argument>
Expand Down Expand Up @@ -637,6 +649,12 @@
<property name="Scope">member</property>
<property name="Target">M:Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.DefaultBindingMetadataProvider.GetBoundConstructor(System.Type)</property>
</attribute>
<attribute fullname="System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute">
<argument>ILLink</argument>
<argument>IL2072</argument>
<property name="Scope">member</property>
<property name="Target">M:Microsoft.AspNetCore.Mvc.ApplicationModels.DefaultApplicationModelProvider.AddReturnTypeMetadata(System.Collections.Generic.IList{Microsoft.AspNetCore.Mvc.ApplicationModels.SelectorModel},System.Reflection.MethodInfo)</property>
</attribute>
<attribute fullname="System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute">
<argument>ILLink</argument>
<argument>IL2072</argument>
Expand Down
8 changes: 0 additions & 8 deletions src/Mvc/Mvc.Core/src/Routing/ActionEndpointFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -543,12 +543,4 @@ private static RequestDelegate CreateRequestDelegate()
return invoker!.InvokeAsync();
};
}

private sealed class InertEndpointBuilder : EndpointBuilder
{
public override Endpoint Build()
{
return new Endpoint(RequestDelegate, new EndpointMetadataCollection(Metadata), DisplayName);
}
}
}
15 changes: 15 additions & 0 deletions src/Mvc/Mvc.Core/src/Routing/InertEndpointBuilder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

namespace Microsoft.AspNetCore.Mvc.Routing;

internal sealed class InertEndpointBuilder : EndpointBuilder
{
public override Endpoint Build()
{
return new Endpoint(RequestDelegate, new EndpointMetadataCollection(Metadata), DisplayName);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1243,6 +1243,45 @@ public void CreateActionModel_InheritedAttributeRoutesOverridden()
Assert.Contains(selectorModel.AttributeRouteModel.Attribute, action.Attributes);
}

[Fact]
public void CreateActionModel_PopulatesReturnTypeEndpointMetadata() {
// Arrange
var builder = new TestApplicationModelProvider();
var typeInfo = typeof(TypedResultsReturningActionsController).GetTypeInfo();
var actionName = nameof(TypedResultsReturningActionsController.Get);

// Act
var action = builder.CreateActionModel(typeInfo, typeInfo.AsType().GetMethod(actionName));

// Assert
Assert.NotNull(action.Selectors);
Assert.All(action.Selectors, selector =>
{
Assert.NotNull(selector.EndpointMetadata);
Assert.Contains(selector.EndpointMetadata, m => m is ProducesResponseTypeMetadata);
});
var metadata = action.Selectors[0].EndpointMetadata.OfType<ProducesResponseTypeMetadata>().Single();
Assert.Equal(200, metadata.StatusCode);
}

[Fact]
public void AddReturnTypeMetadata_ExtractsMetadataFromReturnType()
{
// Arrange
var selector = new SelectorModel();
var selectors = new List<SelectorModel> { selector };
var actionMethod = typeof(TypedResultsReturningActionsController).GetMethod(nameof(TypedResultsReturningActionsController.Get));

// Act
DefaultApplicationModelProvider.AddReturnTypeMetadata(selectors, actionMethod);

// Assert
Assert.NotNull(selector.EndpointMetadata);
Assert.Single(selector.EndpointMetadata);
Assert.IsType<ProducesResponseTypeMetadata>(selector.EndpointMetadata.Single());
Assert.Equal(200, ((ProducesResponseTypeMetadata)selector.EndpointMetadata[0]).StatusCode);
}

[Fact]
public void ControllerDispose_ExplicitlyImplemented_IDisposableMethods_AreTreatedAs_NonActions()
{
Expand Down Expand Up @@ -1711,6 +1750,16 @@ public void Details() { }
public void List() { }
}

private class TypedResultsReturningActionsController : Controller
{
[HttpGet]
public Http.HttpResults.Ok<Foo> Get() => TypedResults.Ok<Foo>(new Foo { Info = "Hello" });
}

public class Foo {
public required string Info { get; set; }
}

private class CustomHttpMethodsAttribute : Attribute, IActionHttpMethodProvider
{
private readonly string[] _methods;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<ItemGroup>
<Reference Include="FSharp.Core" />
<Reference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" />
<Reference Include="Microsoft.AspNetCore.Http.Results" />
<ProjectReference Include="..\..\shared\Mvc.Core.TestCommon\Microsoft.AspNetCore.Mvc.Core.TestCommon.csproj" />
<ProjectReference Include="..\..\shared\Mvc.TestDiagnosticListener\Microsoft.AspNetCore.Mvc.TestDiagnosticListener.csproj" />

Expand Down
25 changes: 25 additions & 0 deletions src/Mvc/test/Mvc.FunctionalTests/ApiExplorerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@
using Microsoft.Extensions.Logging;
using System.Reflection;
using Xunit.Abstractions;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Http;

namespace Microsoft.AspNetCore.Mvc.FunctionalTests;

Expand Down Expand Up @@ -1565,6 +1570,26 @@ public async Task ApiExplorer_LogsInvokedDescriptionProvidersOnStartup()
Assert.Contains(TestSink.Writes, w => w.Message.Equals("Executing API description provider 'JsonPatchOperationsArrayProvider' from assembly Microsoft.AspNetCore.Mvc.NewtonsoftJson v42.42.42.42.", StringComparison.Ordinal));
}

[Fact]
public void ApiExplorer_BuildsMetadataForActionWithTypedResult()
{
var apiDescCollectionProvider = Factory.Server.Services.GetService<IApiDescriptionGroupCollectionProvider>();
var testGroupName = nameof(ApiExplorerWithTypedResultController).Replace("Controller", string.Empty);
var group = apiDescCollectionProvider.ApiDescriptionGroups.Items.Where(i => i.GroupName == testGroupName).SingleOrDefault();
Assert.NotNull(group);
var apiDescription = Assert.Single<ApiDescription>(group.Items);

var responseType = Assert.Single(apiDescription.SupportedResponseTypes);
Assert.Equal(StatusCodes.Status200OK, responseType.StatusCode);
Assert.Equal(typeof(Product), responseType.Type);

Assert.NotNull(apiDescription.ActionDescriptor.EndpointMetadata);
var producesResponseTypeMetadata = apiDescription.ActionDescriptor.EndpointMetadata.OfType<ProducesResponseTypeMetadata>().SingleOrDefault();
Assert.NotNull(producesResponseTypeMetadata);
Assert.Equal(StatusCodes.Status200OK, producesResponseTypeMetadata.StatusCode);
Assert.Equal(typeof(Product), producesResponseTypeMetadata.Type);
}

private IEnumerable<string> GetSortedMediaTypes(ApiExplorerResponseType apiResponseType)
{
return apiResponseType.ResponseFormats
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
<ItemGroup>
<Reference Include="Microsoft.AspNetCore.Mvc" />
<Reference Include="Microsoft.AspNetCore.Mvc.Formatters.Xml" />
<Reference Include="Microsoft.AspNetCore.Http.Results" />
<Reference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" />

<Reference Include="Microsoft.AspNetCore.Server.IISIntegration" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;

namespace ApiExplorerWebSite;

[Route("ApiExplorerWithTypedResult/[Action]")]
public class ApiExplorerWithTypedResultController : Controller
{
[HttpGet]
public Ok<Product> GetProduct() => TypedResults.Ok(new Product { Name = "Test product" });
}
8 changes: 8 additions & 0 deletions src/OpenApi/sample/Controllers/TestController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;

[ApiController]
Expand All @@ -17,6 +18,13 @@ public string GetByIdAndName(RouteParamsContainer paramsContainer)
return paramsContainer.Id + "_" + paramsContainer.Name;
}

[HttpGet]
[Route("/gettypedresult")]
public Ok<MvcTodo> GetTypedResult()
{
return TypedResults.Ok(new MvcTodo("Title", "Description", true));
}

[HttpPost]
[Route("/forms")]
public IActionResult PostForm([FromForm] MvcTodo todo)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,25 @@
}
}
},
"/gettypedresult": {
"get": {
"tags": [
"Test"
],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/MvcTodo"
}
}
}
}
}
}
},
"/forms": {
"post": {
"tags": [
Expand Down Expand Up @@ -88,6 +107,29 @@
}
}
},
"components": {
"schemas": {
"MvcTodo": {
"required": [
"title",
"description",
"isCompleted"
],
"type": "object",
"properties": {
"title": {
"type": "string"
},
"description": {
"type": "string"
},
"isCompleted": {
"type": "boolean"
}
}
}
}
},
"tags": [
{
"name": "Test"
Expand Down
2 changes: 1 addition & 1 deletion src/Shared/EndpointMetadataPopulator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.Http;
internal static class EndpointMetadataPopulator
{
private static readonly MethodInfo PopulateMetadataForParameterMethod = typeof(EndpointMetadataPopulator).GetMethod(nameof(PopulateMetadataForParameter), BindingFlags.NonPublic | BindingFlags.Static)!;
private static readonly MethodInfo PopulateMetadataForEndpointMethod = typeof(EndpointMetadataPopulator).GetMethod(nameof(PopulateMetadataForEndpoint), BindingFlags.NonPublic | BindingFlags.Static)!;
internal static readonly MethodInfo PopulateMetadataForEndpointMethod = typeof(EndpointMetadataPopulator).GetMethod(nameof(PopulateMetadataForEndpoint), BindingFlags.NonPublic | BindingFlags.Static)!;

public static void PopulateMetadata(MethodInfo methodInfo, EndpointBuilder builder, IEnumerable<ParameterInfo>? parameters = null)
{
Expand Down