Skip to content

Respect user set Type for client errors via ProducesResponseType #30509

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

Merged
merged 4 commits into from
Mar 4, 2021
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
10 changes: 8 additions & 2 deletions src/Mvc/Mvc.ApiExplorer/src/ApiResponseTypeProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,15 @@ private ICollection<ApiResponseType> GetApiResponseTypes(
// from the return type.
apiResponseType.Type = type;
}
else if (IsClientError(statusCode) || apiResponseType.IsDefaultResponse)
else if (IsClientError(statusCode))
{
// Determine whether or not the type was provided by the user. If so, favor it over the default
// error type for 4xx client errors if no response type is specified..
var setByDefault = metadataAttribute is ProducesResponseTypeAttribute { IsResponseTypeSetByDefault: true };
apiResponseType.Type = setByDefault ? defaultErrorType : apiResponseType.Type;
}
else if (apiResponseType.IsDefaultResponse)
{
// Use the default error type for "default" responses or 4xx client errors if no response type is specified.
apiResponseType.Type = defaultErrorType;
}
}
Expand Down
16 changes: 15 additions & 1 deletion src/Mvc/Mvc.Core/src/ProducesResponseTypeAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@ public class ProducesResponseTypeAttribute : Attribute, IApiResponseMetadataProv
{
/// <summary>
/// Initializes an instance of <see cref="ProducesResponseTypeAttribute"/>.
/// </summary>
/// </summary>
/// <param name="statusCode">The HTTP response status code.</param>
public ProducesResponseTypeAttribute(int statusCode)
: this(typeof(void), statusCode)
{
IsResponseTypeSetByDefault = true;
}

/// <summary>
Expand All @@ -31,6 +32,7 @@ public ProducesResponseTypeAttribute(Type type, int statusCode)
{
Type = type ?? throw new ArgumentNullException(nameof(type));
StatusCode = statusCode;
IsResponseTypeSetByDefault = false;
}

/// <summary>
Expand All @@ -43,6 +45,18 @@ public ProducesResponseTypeAttribute(Type type, int statusCode)
/// </summary>
public int StatusCode { get; set; }

/// <summary>
/// Used to distinguish a `Type` set by default in the constructor versus
/// one provided by the user.
///
/// When <see langword="false"/>, then <see cref="Type"/> is set by user.
///
/// When <see langword="true"/>, then <see cref="Type"/> is set by by
/// default in the constructor
/// </summary>
/// <value></value>
internal bool IsResponseTypeSetByDefault { get; }

/// <inheritdoc />
void IApiResponseMetadataProvider.SetContentTypes(MediaTypeCollection contentTypes)
{
Expand Down
23 changes: 23 additions & 0 deletions src/Mvc/test/Mvc.FunctionalTests/ApiExplorerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1461,6 +1461,29 @@ public async Task ApiConvention_ForActionWithApiConventionMethod()
});
}

[Theory]
[InlineData("ActionWithNoExplicitType", typeof(ProblemDetails))]
[InlineData("ActionWithVoidType", typeof(void))]
public async Task ApiAction_ForActionWithVoidResponseType(string path, Type type)
{
// Act
var response = await Client.GetAsync($"http://localhost/ApiExplorerVoid/{path}");

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(type.FullName, responseType.ResponseType);
Assert.Equal(401, 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
@@ -0,0 +1,20 @@

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using Microsoft.AspNetCore.Mvc;

namespace ApiExplorerWebSite
{
[Route("ApiExplorerVoid/[action]")]
[ApiController]
public class ApiExplorerVoidController : Controller
{
[ProducesResponseType(typeof(void), 401)]
public IActionResult ActionWithVoidType() => Ok();

[ProducesResponseType(401)]
public IActionResult ActionWithNoExplicitType() => Ok();

}
}