Skip to content

Commit

Permalink
Fixed the issue. Will be adding the tests as a separate commit. (#60096)
Browse files Browse the repository at this point in the history
# Include typed result metadata in the action descriptors for MVC Controller actions

## Description

The endpoint metadata wasn't being captured in ActionModel during the ApplicationModel creation. This is addressed by the change in the DefaultApplicationModelProvider class. The metadata is now being extracted based on the return type of the action and then the selectors associated with the action are populated with that metadata, as that's what is being used later on for populating the ActionDescriptor's EndpointMetadata.

Fixes #44988
  • Loading branch information
mkArtakMSFT authored Feb 4, 2025
1 parent f5ce3f3 commit 43b5fbf
Show file tree
Hide file tree
Showing 12 changed files with 207 additions and 9 deletions.
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

0 comments on commit 43b5fbf

Please sign in to comment.