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

Fix FromForm without WithOpenApi schemas #3133

Original file line number Diff line number Diff line change
Expand Up @@ -422,45 +422,43 @@ private async Task<OpenApiOperation> GenerateOpenApiOperationFromMetadataAsync(A
}
}

var requestContentTypes = operation.RequestBody?.Content?.Values;
var requestContentTypes = operation.RequestBody?.Content?.Keys;
if (requestContentTypes is not null)
{
foreach (var content in requestContentTypes)
foreach (var contentType in requestContentTypes)
{
content.Encoding = new Dictionary<string, OpenApiEncoding>();
var requestParameters = apiDescription.ParameterDescriptions.Where(desc => desc.IsFromBody() || desc.IsFromForm());
var countOfParameters = requestParameters.Count();
if (countOfParameters > 0)
var contentTypeValue = operation.RequestBody.Content[contentType];
var fromFormParameters = apiDescription.ParameterDescriptions.Where(desc => desc.IsFromForm()).ToList();
ApiParameterDescription bodyParameterDescription = null;
if (fromFormParameters.Count > 0)
{
ApiParameterDescription bodyParameterDescription = null;
if (countOfParameters == 1)
var generatedContentTypeValue = GenerateRequestBodyFromFormParameters(
apiDescription,
schemaRepository,
fromFormParameters,
[contentType]).Content[contentType];

contentTypeValue.Schema = generatedContentTypeValue.Schema;
contentTypeValue.Encoding = generatedContentTypeValue.Encoding;
}
else
{
bodyParameterDescription = apiDescription.ParameterDescriptions.Single(desc => desc.IsFromBody());
if (bodyParameterDescription is not null)
{
var requestParameter = requestParameters.First();
content.Schema = GenerateSchemaIncludingFormFile(requestParameter, GenerateSchema(
requestParameter.ModelMetadata.ModelType,
contentTypeValue.Schema = GenerateSchema(
bodyParameterDescription.ModelMetadata.ModelType,
schemaRepository,
requestParameter.PropertyInfo(),
requestParameter.ParameterInfo()), content);

bodyParameterDescription = requestParameter.IsFromBody() ? requestParameter : null;
}
else
{
content.Schema = new OpenApiSchema()
{
AllOf = requestParameters.Select(s =>
GenerateSchemaIncludingFormFile(s, GenerateSchema(
s.ModelMetadata.ModelType,
schemaRepository,
s.PropertyInfo(),
s.ParameterInfo()), content))
.ToList()
};
bodyParameterDescription.PropertyInfo(),
bodyParameterDescription.ParameterInfo());
}
}

if (fromFormParameters.Count > 0 || bodyParameterDescription is not null)
{
var filterContext = new RequestBodyFilterContext(
bodyParameterDescription: bodyParameterDescription,
formParameterDescriptions: bodyParameterDescription is null ? requestParameters : null,
formParameterDescriptions: bodyParameterDescription is null ? fromFormParameters : null,
schemaGenerator: _schemaGenerator,
schemaRepository: schemaRepository);

Expand All @@ -474,25 +472,6 @@ private async Task<OpenApiOperation> GenerateOpenApiOperationFromMetadataAsync(A
filter.Apply(operation.RequestBody, filterContext);
}
}

static OpenApiSchema GenerateSchemaIncludingFormFile(ApiParameterDescription apiParameterDescription, OpenApiSchema generatedSchema, OpenApiMediaType mediaType)
{
if (generatedSchema.Reference is null && apiParameterDescription.IsFromForm())
{
mediaType.Encoding.Add(apiParameterDescription.Name, new OpenApiEncoding { Style = ParameterStyle.Form });
return new OpenApiSchema()
{
Type = "object",
Properties = new Dictionary<string, OpenApiSchema>()
{
[apiParameterDescription.Name] = generatedSchema
},
Required = apiParameterDescription.IsRequired ? new SortedSet<string>() { apiParameterDescription.Name } : null
};
}
return generatedSchema;
}

}
}

Expand Down Expand Up @@ -721,7 +700,7 @@ private OpenApiSchema GenerateSchema(
}
else if (formParameters.Count > 0)
{
requestBody = GenerateRequestBodyFromFormParameters(apiDescription, schemaRepository, formParameters);
requestBody = GenerateRequestBodyFromFormParameters(apiDescription, schemaRepository, formParameters, null);

filterContext = new RequestBodyFilterContext(
bodyParameterDescription: null,
Expand Down Expand Up @@ -819,13 +798,21 @@ private static IEnumerable<string> InferRequestContentTypes(ApiDescription apiDe
private OpenApiRequestBody GenerateRequestBodyFromFormParameters(
ApiDescription apiDescription,
SchemaRepository schemaRepository,
IEnumerable<ApiParameterDescription> formParameters)
IEnumerable<ApiParameterDescription> formParameters,
IEnumerable<string> contentTypes)
{
var contentTypes = InferRequestContentTypes(apiDescription);
contentTypes = contentTypes.Any() ? contentTypes : ["multipart/form-data"];
if (contentTypes is null)
{
contentTypes = InferRequestContentTypes(apiDescription);
contentTypes = contentTypes.Any() ? contentTypes : ["multipart/form-data"];
}

var schema = GenerateSchemaFromFormParameters(formParameters, schemaRepository);

var totalProperties = schema.AllOf
?.FirstOrDefault(s => s.Properties.Count > 0)
?.Properties ?? schema.Properties;

return new OpenApiRequestBody
{
Content = contentTypes
Expand All @@ -834,7 +821,7 @@ private OpenApiRequestBody GenerateRequestBodyFromFormParameters(
contentType => new OpenApiMediaType
{
Schema = schema,
Encoding = schema.Properties.ToDictionary(
Encoding = totalProperties.ToDictionary(
entry => entry.Key,
entry => new OpenApiEncoding { Style = ParameterStyle.Form }
)
Expand All @@ -849,13 +836,9 @@ private OpenApiSchema GenerateSchemaFromFormParameters(
{
var properties = new Dictionary<string, OpenApiSchema>();
var requiredPropertyNames = new List<string>();

var ownSchemas = new List<OpenApiSchema>();
foreach (var formParameter in formParameters)
{
var name = _options.DescribeAllParametersInCamelCase
? formParameter.Name.ToCamelCase()
: formParameter.Name;

var propertyInfo = formParameter.PropertyInfo();
if (!propertyInfo?.HasAttribute<SwaggerIgnoreAttribute>() ?? true)
{
Expand All @@ -867,19 +850,52 @@ private OpenApiSchema GenerateSchemaFromFormParameters(
formParameter.ParameterInfo())
: new OpenApiSchema { Type = "string" };

properties.Add(name, schema);

if (formParameter.IsRequiredParameter())
requiredPropertyNames.Add(name);
if (schema.Reference is null
|| (formParameter.Type is not null && (Nullable.GetUnderlyingType(formParameter.Type) ?? formParameter.Type).IsEnum))
{
var name = _options.DescribeAllParametersInCamelCase
? formParameter.Name.ToCamelCase()
: formParameter.Name;
properties.Add(name, schema);
if (formParameter.IsRequiredParameter())
{
requiredPropertyNames.Add(name);
}
}
else
{
ownSchemas.Add(schema);
}
}
}

return new OpenApiSchema
if (ownSchemas.Count > 0)
{
Type = "object",
Properties = properties,
Required = new SortedSet<string>(requiredPropertyNames)
};
bool isAllOf = ownSchemas.Count > 1 || (ownSchemas.Count > 0 && properties.Count > 0);
if (isAllOf)
{
var allOfSchema = new OpenApiSchema()
{
AllOf = ownSchemas
};
if (properties.Count > 0)
{
allOfSchema.AllOf.Add(GenerateSchemaForProperties(properties, requiredPropertyNames));
}
return allOfSchema;
}
return ownSchemas.First();
}

return GenerateSchemaForProperties(properties, requiredPropertyNames);

static OpenApiSchema GenerateSchemaForProperties(Dictionary<string, OpenApiSchema> properties, List<string> requiredPropertyNames) =>
new()
{
Type = "object",
Properties = properties,
Required = new SortedSet<string>(requiredPropertyNames)
};
}

private OpenApiResponses GenerateResponses(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,10 @@ public void Apply(OpenApiRequestBody requestBody, RequestBodyFilterContext conte
&& (properties.TryGetValue(formParameter.Name, out var value) || properties.TryGetValue(formParameter.Name.ToCamelCase(), out value)))
{
var (summary, example) = GetParamTags(parameterFromForm);
value.Description = summary;
value.Description ??= summary;
if (!string.IsNullOrEmpty(example))
{
value.Example = XmlCommentsExampleHelper.Create(context.SchemaRepository, value, example);
value.Example ??= XmlCommentsExampleHelper.Create(context.SchemaRepository, value, example);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -665,6 +665,73 @@
x-purpose: test
}
},
/registrationsWithEnumParameter: {
post: {
tags: [
FromFormParams
],
summary: Form parameters with description,
requestBody: {
content: {
multipart/form-data: {
schema: {
type: object,
properties: {
name: {
type: string,
description: Summary for Name,
example: MyName
},
phoneNumbers: {
type: array,
items: {
type: integer,
format: int32
},
description: Sumary for PhoneNumbers
},
logLevel: {
$ref: #/components/schemas/LogLevel
},
formFile: {
type: string,
description: Description for file,
format: binary
},
dateTimeKind: {
$ref: #/components/schemas/DateTimeKind
}
}
},
encoding: {
name: {
style: form
},
phoneNumbers: {
style: form
},
logLevel: {
style: form
},
formFile: {
style: form
},
dateTimeKind: {
style: form
}
}
}
},
x-purpose: test
},
responses: {
200: {
description: OK
}
},
x-purpose: test
}
},
/country/validate: {
get: {
tags: [
Expand Down Expand Up @@ -1283,13 +1350,35 @@
},
additionalProperties: false
},
DateTimeKind: {
enum: [
0,
1,
2
],
type: integer,
format: int32
},
DiscountType: {
enum: [
Percentage,
Amount
],
type: string
},
LogLevel: {
enum: [
0,
1,
2,
3,
4,
5,
6
],
type: integer,
format: int32
},
Order: {
type: object,
properties: {
Expand Down
Loading