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

ApiExplorer Support for HttpResults types for Controllers #57464

Open
wants to merge 8 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
25 changes: 25 additions & 0 deletions src/Mvc/Mvc.Core/src/Routing/ActionEndpointFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -353,11 +353,13 @@ private static void AddActionDataToBuilder(

// Add metadata inferred from the parameter and/or return type before action-specific metadata.
// MethodInfo *should* never be null given a ControllerActionDescriptor, but this is unenforced.
var metadataCountBeforePopulating = builder.Metadata.Count;
if (controllerActionDescriptor?.MethodInfo is not null)
{
EndpointMetadataPopulator.PopulateMetadata(controllerActionDescriptor.MethodInfo, builder);
}

var metadataCountAfterPopulating = builder.Metadata.Count;
// Add action-specific metadata early so it has a low precedence
if (action.EndpointMetadata != null)
{
Expand All @@ -369,6 +371,29 @@ private static void AddActionDataToBuilder(

builder.Metadata.Add(action);

if (metadataCountAfterPopulating != metadataCountBeforePopulating)
jgarciadelanoceda marked this conversation as resolved.
Show resolved Hide resolved
{
action.EndpointMetadata ??= [];
HashSet<int> producesResponseMetadataByAttribute = [];
foreach (var endpointMetadataInAttributes in action.EndpointMetadata)
{
if (endpointMetadataInAttributes is IProducesResponseTypeMetadata metadataInAttributes
&& !producesResponseMetadataByAttribute.Contains(metadataInAttributes.StatusCode))
{
producesResponseMetadataByAttribute.Add(metadataInAttributes.StatusCode);
}
}

foreach (var endpointMetadata in builder.Metadata)
{
if (endpointMetadata is IProducesResponseTypeMetadata metadata
&& !producesResponseMetadataByAttribute.Contains(metadata.StatusCode))
{
action.EndpointMetadata.Add(metadata);
}
}
}

// MVC guarantees that when two of it's endpoints have the same route name they are equivalent.
//
// The case for this looks like:
Expand Down
83 changes: 80 additions & 3 deletions src/Mvc/test/Mvc.FunctionalTests/ApiExplorerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@

using System.Net;
using System.Net.Http;
using System.Reflection;
using ApiExplorerWebSite;
using Microsoft.AspNetCore.InternalTesting;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.InternalTesting;
using Newtonsoft.Json;
using Microsoft.Extensions.Logging;
using System.Reflection;
using Xunit.Abstractions;

namespace Microsoft.AspNetCore.Mvc.FunctionalTests;
Expand Down Expand Up @@ -1565,6 +1564,84 @@ 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 async Task ApiExplorer_SupportsIResults()
{
// Act
var response = await Client.GetAsync($"http://localhost/ApiExplorerHttpResultsController/GetOfT");
var responseBody = await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(responseBody);

//Assert
var description = Assert.Single(result);
Assert.Collection(
description.SupportedResponseTypes.OrderBy(r => r.StatusCode),
responseType =>
{
Assert.Equal(typeof(int).FullName, responseType.ResponseType);
Assert.Equal(200, responseType.StatusCode);
Assert.False(responseType.IsDefaultResponse);
},
responseType =>
{
Assert.Equal(typeof(DateTime).FullName, responseType.ResponseType);
Assert.Equal(404, responseType.StatusCode);
Assert.False(responseType.IsDefaultResponse);
});
}

[Fact]
public async Task ApiExplorer_SupportsIResultsWhenNoType()
{
// Act
var response = await Client.GetAsync($"http://localhost/ApiExplorerHttpResultsController/GetWithNotFoundWithNoType");
var responseBody = await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(responseBody);

//Assert
var description = Assert.Single(result);
Assert.Collection(
description.SupportedResponseTypes.OrderBy(r => r.StatusCode),
responseType =>
{
Assert.Equal(typeof(int).FullName, responseType.ResponseType);
Assert.Equal(200, responseType.StatusCode);
Assert.False(responseType.IsDefaultResponse);
},
responseType =>
{
Assert.Equal(typeof(void).FullName, responseType.ResponseType);
Assert.Equal(404, responseType.StatusCode);
Assert.False(responseType.IsDefaultResponse);
});
}

[Fact]
public async Task ApiExplorer_SupportsIResultsWhenDifferentProduceType()
{
// Act
var response = await Client.GetAsync($"http://localhost/ApiExplorerHttpResultsController/GetWithDifferentProduceType");
var responseBody = await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(responseBody);

//Assert
var description = Assert.Single(result);
Assert.Collection(
description.SupportedResponseTypes.OrderBy(r => r.StatusCode),
responseType =>
{
Assert.Equal(typeof(long).FullName, responseType.ResponseType);
Assert.Equal(200, responseType.StatusCode);
Assert.False(responseType.IsDefaultResponse);
},
responseType =>
{
Assert.Equal(typeof(void).FullName, responseType.ResponseType);
Assert.Equal(404, responseType.StatusCode);
Assert.False(responseType.IsDefaultResponse);
});
}

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

<Reference Include="Microsoft.AspNetCore.Http.Results" />
<Reference Include="Microsoft.AspNetCore.Server.IISIntegration" />
<Reference Include="Microsoft.AspNetCore.Server.Kestrel" />
<Reference Include="Microsoft.AspNetCore.StaticFiles" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// 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.Controllers;

public class ApiExplorerHttpResultsController : Controller
{
[HttpGet("ApiExplorerHttpResultsController/GetOfT")]
public Results<Ok<int>, NotFound<DateTime>> Get()
{
return Random.Shared.Next() % 2 == 0
? TypedResults.Ok(0)
: TypedResults.NotFound(DateTime.Now);
}

[HttpGet("ApiExplorerHttpResultsController/GetWithNotFoundWithNoType")]
public async Task<Results<Ok<int>, NotFound>> GetWithNotFoundWithNoType()
{
await Task.Delay(1);
return Random.Shared.Next() % 2 == 0
? TypedResults.Ok(0)
: TypedResults.NotFound();
}
[ProducesResponseType(200, Type = typeof(long))]
[HttpGet("ApiExplorerHttpResultsController/GetWithDifferentProduceType")]
public async Task<Results<Ok<int>, NotFound>> GetWithDifferentProduceType()
{
await Task.Delay(1);
return Random.Shared.Next() % 2 == 0
? TypedResults.Ok(0)
: TypedResults.NotFound();
}
}
10 changes: 10 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,15 @@ public string GetByIdAndName(RouteParamsContainer paramsContainer)
return paramsContainer.Id + "_" + paramsContainer.Name;
}

[HttpGet]
[Route("/getbyidandnameWithIResults/{id}/{name}")]
public Results<Ok<string>, NotFound> GetByIdAndNameWithIResults(RouteParamsContainer paramsContainer)
{
return Random.Shared.Next() % 2 == 0 ?
TypedResults.Ok(paramsContainer.Id + "_" + paramsContainer.Name)
: TypedResults.NotFound();
}

[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,49 @@
}
}
},
"/getbyidandnameWithIResults/{id}/{name}": {
"get": {
"tags": [
"Test"
],
"parameters": [
{
"name": "Id",
"in": "path",
"required": true,
"schema": {
"type": "integer",
"format": "int32"
}
},
{
"name": "Name",
"in": "path",
"required": true,
"schema": {
"minLength": 5,
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"minLength": 5,
"type": "string"
}
}
}
},
"404": {
"description": "Not Found"
}
}
}
},
"/forms": {
"post": {
"tags": [
Expand Down
Loading