internal static OpenApiSchema AssignAttributeMetadata(this OpenApiSchema schema, IEnumerable <object> attributes) { foreach (var attribute in attributes) { if (attribute is DefaultValueAttribute defaultValue) { schema.Default = OpenApiPrimitiveFactory.CreateFrom(defaultValue.Value); } if (attribute is RegularExpressionAttribute regex) { schema.Pattern = regex.Pattern; } if (attribute is RangeAttribute range) { if (decimal.TryParse(range.Maximum.ToString(), out decimal maximum)) { schema.Maximum = maximum; } if (decimal.TryParse(range.Minimum.ToString(), out decimal minimum)) { schema.Minimum = minimum; } } if (attribute is MinLengthAttribute minLength) { schema.MinLength = minLength.Length; } if (attribute is MaxLengthAttribute maxLength) { schema.MaxLength = maxLength.Length; } if (attribute is StringLengthAttribute stringLength) { schema.MinLength = stringLength.MinimumLength; schema.MaxLength = stringLength.MaximumLength; } if (attribute is DataTypeAttribute dataTypeAttribute && schema.Type == "string") { if (DataTypeFormatMap.TryGetValue(dataTypeAttribute.DataType, out string format)) { schema.Format = format; } } } return(schema); }
private OpenApiParameter GenerateParameter( ApiDescription apiDescription, ApiParameterDescription apiParameter, ISchemaRegistry schemaRegistry) { apiParameter.GetAdditionalMetadata( apiDescription, out ParameterInfo parameterInfo, out PropertyInfo propertyInfo, out IEnumerable <object> parameterOrPropertyAttributes); var name = _options.DescribeAllParametersInCamelCase ? apiParameter.Name.ToCamelCase() : apiParameter.Name; var location = ParameterLocationMap.ContainsKey(apiParameter.Source) ? ParameterLocationMap[apiParameter.Source] : ParameterLocation.Query; var isRequired = (apiParameter.IsFromPath()) || parameterOrPropertyAttributes.Any(attr => RequiredAttributeTypes.Contains(attr.GetType())); var schema = (apiParameter.Type != null) ? schemaRegistry.GetOrRegister(apiParameter.Type) : new OpenApiSchema { Type = "string" }; // If it corresponds to an optional action parameter, assign the default value if (parameterInfo?.DefaultValue != null && schema.Reference == null) { schema.Default = OpenApiPrimitiveFactory.CreateFrom(parameterInfo.DefaultValue); } var parameter = new OpenApiParameter { Name = name, In = location, Required = isRequired, Schema = schema }; var filterContext = new ParameterFilterContext(apiParameter, schemaRegistry, parameterInfo, propertyInfo); foreach (var filter in _options.ParameterFilters) { filter.Apply(parameter, filterContext); } return(parameter); }
private static IOpenApiPrimitive ConvertToOpenApiType(string value, Type type) { object typedExample; try { typedExample = TypeDescriptor.GetConverter(type).ConvertFrom(value); } catch (Exception) { return(new OpenApiString(value)); } return(OpenApiPrimitiveFactory.CreateFrom(typedExample) ?? new OpenApiString(value)); }