Skip to content

Add support for stating accepts/consumes metadata is required or not #35875

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 19 commits into from
Sep 3, 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
5 changes: 5 additions & 0 deletions src/Http/Http.Abstractions/src/Metadata/IAcceptsMetadata.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,10 @@ public interface IAcceptsMetadata
/// Gets the type being read from the request.
/// </summary>
Type? RequestType { get; }

/// <summary>
/// Gets a value that determines if the request body is optional.
/// </summary>
bool IsOptional { get; }
}
}
1 change: 1 addition & 0 deletions src/Http/Http.Abstractions/src/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ Microsoft.AspNetCore.Http.IResult
Microsoft.AspNetCore.Http.IResult.ExecuteAsync(Microsoft.AspNetCore.Http.HttpContext! httpContext) -> System.Threading.Tasks.Task!
Microsoft.AspNetCore.Http.Metadata.IAcceptsMetadata
Microsoft.AspNetCore.Http.Metadata.IAcceptsMetadata.ContentTypes.get -> System.Collections.Generic.IReadOnlyList<string!>!
Microsoft.AspNetCore.Http.Metadata.IAcceptsMetadata.IsOptional.get -> bool
Microsoft.AspNetCore.Http.Metadata.IAcceptsMetadata.RequestType.get -> System.Type?
Microsoft.AspNetCore.Http.Metadata.IFromBodyMetadata
Microsoft.AspNetCore.Http.Metadata.IFromBodyMetadata.AllowEmpty.get -> bool
Expand Down
5 changes: 2 additions & 3 deletions src/Http/Http.Extensions/src/RequestDelegateFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,7 @@ public static partial class RequestDelegateFactory
private static ParameterExpression TempSourceStringExpr => TryParseMethodCache.TempSourceStringExpr;
private static readonly BinaryExpression TempSourceStringNotNullExpr = Expression.NotEqual(TempSourceStringExpr, Expression.Constant(null));
private static readonly BinaryExpression TempSourceStringNullExpr = Expression.Equal(TempSourceStringExpr, Expression.Constant(null));

private static readonly AcceptsMetadata DefaultAcceptsMetadata = new(new[] { "application/json" });
private static readonly string[] DefaultAcceptsContentType = new[] { "application/json" };

/// <summary>
/// Creates a <see cref="RequestDelegate"/> implementation for <paramref name="handler"/>.
Expand Down Expand Up @@ -879,11 +878,11 @@ private static Expression BindParameterFromBody(ParameterInfo parameter, bool al
}
}

factoryContext.Metadata.Add(DefaultAcceptsMetadata);
var isOptional = IsOptionalParameter(parameter, factoryContext);

factoryContext.JsonRequestBodyType = parameter.ParameterType;
factoryContext.AllowEmptyRequestBody = allowEmpty || isOptional;
factoryContext.Metadata.Add(new AcceptsMetadata(parameter.ParameterType, factoryContext.AllowEmptyRequestBody, DefaultAcceptsContentType));

if (!factoryContext.AllowEmptyRequestBody)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -290,14 +290,13 @@ public void MapPost_BuildsEndpointWithCorrectEndpointMetadata()
// Trigger Endpoint build by calling getter.
var endpoint = Assert.Single(dataSource.Endpoints);

var endpointMetadata = endpoint.Metadata.GetOrderedMetadata<IAcceptsMetadata>();
var endpointMetadata = endpoint.Metadata.GetMetadata<IAcceptsMetadata>();

Assert.NotNull(endpointMetadata);
Assert.Equal(2, endpointMetadata.Count);
Assert.False(endpointMetadata!.IsOptional);
Assert.Equal(typeof(Todo), endpointMetadata.RequestType);
Assert.Equal(new[] { "application/xml" }, endpointMetadata.ContentTypes);

var lastAddedMetadata = endpointMetadata[^1];

Assert.Equal(typeof(Todo), lastAddedMetadata.RequestType);
Assert.Equal(new[] { "application/xml" }, lastAddedMetadata.ContentTypes);
}

[Fact]
Expand Down Expand Up @@ -567,13 +566,13 @@ public TestConsumesAttribute(Type requestType, string contentType, params string
}

IReadOnlyList<string> IAcceptsMetadata.ContentTypes => _contentTypes;

Type? IAcceptsMetadata.RequestType => _requestType;

bool IAcceptsMetadata.IsOptional => false;

Type? _requestType;

List<string> _contentTypes = new();

}

class Todo
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,6 @@ private ApiDescription CreateApiDescription(RouteEndpoint routeEndpoint, string
},
};

var hasJsonBody = false;

foreach (var parameter in methodInfo.GetParameters())
{
var parameterDescription = CreateApiParameterDescription(parameter, routeEndpoint.RoutePattern);
Expand All @@ -113,33 +111,37 @@ private ApiDescription CreateApiDescription(RouteEndpoint routeEndpoint, string
continue;
}

if (parameterDescription.Source == BindingSource.Body)
{
hasJsonBody = true;
}

apiDescription.ParameterDescriptions.Add(parameterDescription);
}

// Get custom attributes for the handler. ConsumesAttribute is one of the examples.
var acceptsRequestType = routeEndpoint.Metadata.GetMetadata<IAcceptsMetadata>()?.RequestType;
if (acceptsRequestType is not null)
// Get IAcceptsMetadata.
var acceptsMetadata = routeEndpoint.Metadata.GetMetadata<IAcceptsMetadata>();
if (acceptsMetadata is not null)
{
var acceptsRequestType = acceptsMetadata.RequestType;
var isOptional = acceptsMetadata.IsOptional;
var parameterDescription = new ApiParameterDescription
{
Name = acceptsRequestType.Name,
ModelMetadata = CreateModelMetadata(acceptsRequestType),
Name = acceptsRequestType is not null ? acceptsRequestType.Name : typeof(void).Name,
ModelMetadata = CreateModelMetadata(acceptsRequestType ?? typeof(void)),
Source = BindingSource.Body,
Type = acceptsRequestType,
IsRequired = true,
Type = acceptsRequestType ?? typeof(void),
IsRequired = !isOptional,
};

apiDescription.ParameterDescriptions.Add(parameterDescription);

var supportedRequestFormats = apiDescription.SupportedRequestFormats;

foreach (var contentType in acceptsMetadata.ContentTypes)
{
supportedRequestFormats.Add(new ApiRequestFormat
{
MediaType = contentType
});
}
}

AddSupportedRequestFormats(apiDescription.SupportedRequestFormats, hasJsonBody, routeEndpoint.Metadata);
AddSupportedResponseTypes(apiDescription.SupportedResponseTypes, methodInfo.ReturnType, routeEndpoint.Metadata);

AddActionDescriptorEndpointMetadata(apiDescription.ActionDescriptor, routeEndpoint.Metadata);

return apiDescription;
Expand All @@ -150,7 +152,8 @@ private ApiDescription CreateApiDescription(RouteEndpoint routeEndpoint, string
var (source, name, allowEmpty) = GetBindingSourceAndName(parameter, pattern);

// Services are ignored because they are not request parameters.
if (source == BindingSource.Services)
// We ignore/skip body parameter because the value will be retrieved from the IAcceptsMetadata.
if (source == BindingSource.Services || source == BindingSource.Body)
{
return null;
}
Expand Down Expand Up @@ -222,33 +225,6 @@ private ApiDescription CreateApiDescription(RouteEndpoint routeEndpoint, string
}
}

private static void AddSupportedRequestFormats(
IList<ApiRequestFormat> supportedRequestFormats,
bool hasJsonBody,
EndpointMetadataCollection endpointMetadata)
{
var requestMetadata = endpointMetadata.GetOrderedMetadata<IApiRequestMetadataProvider>();
var declaredContentTypes = DefaultApiDescriptionProvider.GetDeclaredContentTypes(requestMetadata);

if (declaredContentTypes.Count > 0)
{
foreach (var contentType in declaredContentTypes)
{
supportedRequestFormats.Add(new ApiRequestFormat
{
MediaType = contentType,
});
}
}
else if (hasJsonBody)
{
supportedRequestFormats.Add(new ApiRequestFormat
{
MediaType = "application/json",
});
}
}

private static void AddSupportedResponseTypes(
IList<ApiResponseType> supportedResponseTypes,
Type returnType,
Expand Down
Loading