コード例 #1
0
        private OpenApiParameter GetParameter(IDictionary <string, OpenApiSchema> schemas, Type schemaType, string route, string verb, string paramName, string paramIn, ApiAllowableValuesAttribute allowableValueAttrs = null)
        {
            OpenApiParameter parameter;

            if (IsDictionaryType(schemaType))
            {
                parameter = new OpenApiParameter
                {
                    In     = paramIn,
                    Name   = paramName,
                    Schema = GetDictionarySchema(schemas, schemaType, route, verb)
                };
            }
            else if (IsListType(schemaType))
            {
                parameter = GetListParameter(schemas, schemaType, route, verb, paramName, paramIn);
            }
            else if (IsSwaggerScalarType(schemaType))
            {
                parameter = new OpenApiParameter
                {
                    In       = paramIn,
                    Name     = paramName,
                    Type     = GetSwaggerTypeName(schemaType),
                    Format   = GetSwaggerTypeFormat(schemaType, route, verb),
                    Enum     = GetEnumValues(allowableValueAttrs),
                    Nullable = IsRequiredType(schemaType) ? false : (bool?)null
                };
            }
            else
            {
                parameter = new OpenApiParameter
                {
                    In     = paramIn,
                    Name   = paramName,
                    Schema = new OpenApiSchema {
                        Ref = "#/definitions/" + GetSchemaTypeName(schemaType)
                    }
                };
            }

            return(parameter);
        }
コード例 #2
0
        /// <inheritdoc/>
        protected override void SetParameters(OpenApiOperation operation)
        {
            base.SetParameters(operation);

            // $select
            OpenApiParameter parameter = Context.CreateSelect(Singleton);

            if (parameter != null)
            {
                operation.Parameters.Add(parameter);
            }

            // $expand
            parameter = Context.CreateExpand(Singleton);
            if (parameter != null)
            {
                operation.Parameters.Add(parameter);
            }
        }
コード例 #3
0
        public void ValidateRequiredIsTrueWhenInIsPathInParameter()
        {
            // Arrange
            var parameter = new OpenApiParameter()
            {
                Name = "name",
                In   = ParameterLocation.Path
            };

            // Act
            var errors = parameter.Validate(ValidationRuleSet.GetDefaultRuleSet());

            // Assert
            errors.Should().NotBeEmpty();
            errors.Select(e => e.Message).Should().BeEquivalentTo(new[]
            {
                "\"required\" must be true when parameter location is \"path\""
            });
        }
コード例 #4
0
        public static OpenApiParameter LoadParameter(ParseNode node)
        {
            var mapNode = node.CheckMapNode("parameter");

            var pointer = mapNode.GetReferencePointer();

            if (pointer != null)
            {
                return(mapNode.GetReferencedObject <OpenApiParameter>(ReferenceType.Parameter, pointer));
            }

            var parameter = new OpenApiParameter();

            ParseMap(mapNode, parameter, _parameterFixedFields, _parameterPatternFields);
            ProcessAnyFields(mapNode, parameter, _parameterAnyFields);
            ProcessAnyMapFields(mapNode, parameter, _parameterAnyMapOpenApiExampleFields);

            return(parameter);
        }
コード例 #5
0
        public void CheckThatParsedAttributeHasCorrectlySetDataTypeAndFormat()
        {
            OpenApiParameter parameter = new OpenApiParameter
            {
                In     = ParameterLocation.Path,
                Schema = new OpenApiSchema {
                    Type = "string", Format = null
                },
                Example  = null,
                Examples = new Dictionary <string, OpenApiExample>()
            };

            var parsedAttribute = AttributeParser.ParseAttribute(parameter);

            Assert.IsNotNull(parsedAttribute);
            Assert.IsTrue(!string.IsNullOrEmpty(parsedAttribute.ExampleValue));
            Assert.AreEqual(parameter.Schema.Type, parsedAttribute.Type);
            Assert.AreEqual(parameter.Schema.Format, parsedAttribute.Format);
        }
コード例 #6
0
        public void GivenIHaveAnOpenApiOperationWithAnArgumentTypeThatListsAnUndefinedPropertyAsRequired()
        {
            var intSchema = new OpenApiSchema
            {
                Type   = "integer",
                Format = "int32",
            };
            var schemaListingAnUndefinedPropertyAsRequired = new OpenApiSchema
            {
                Type = "object",
                AdditionalPropertiesAllowed = false,
                Properties = new Dictionary <string, OpenApiSchema>
                {
                    { "RightSpelling", intSchema },
                },
                Required = new HashSet <string> {
                    "WriteSpelngi"
                },
            };
            var parameter = new OpenApiParameter
            {
                Schema = schemaListingAnUndefinedPropertyAsRequired,
            };

            this.operation = new OpenApiOperation {
                OperationId = "Ic"
            };
            this.operation.Responses.Add(
                "200",
                new OpenApiResponse());
            this.operation.Parameters.Add(parameter);

            this.document = new OpenApiDocument
            {
                Paths = new OpenApiPaths(),
            };
            this.document.Paths.Add("/", new OpenApiPathItem {
                Operations = new Dictionary <OperationType, OpenApiOperation> {
                    { OperationType.Get, this.operation }
                }
            });
        }
コード例 #7
0
        private OpenApiParameter CreatePrimitiveSwaggerParameter(ContextualType contextualParameter, JsonTypeDescription typeDescription)
        {
            OpenApiParameter operationParameter;

            if (typeDescription.RequiresSchemaReference(_settings.TypeMappers))
            {
                var referencedSchema = _settings.SchemaGenerator.Generate(contextualParameter, _schemaResolver);

                operationParameter = new OpenApiParameter
                {
                    Type         = typeDescription.Type,
                    CustomSchema = new JsonSchema {
                        Reference = referencedSchema.ActualSchema
                    }
                };

                // Copy enumeration for compatibility with other tools which do not understand x-schema.
                // The enumeration will be ignored by NSwag and only the x-schema is processed
                if (referencedSchema.ActualSchema.IsEnumeration)
                {
                    operationParameter.Enumeration.Clear();
                    foreach (var item in referencedSchema.ActualSchema.Enumeration)
                    {
                        operationParameter.Enumeration.Add(item);
                    }
                }

                _settings.SchemaGenerator.ApplyDataAnnotations(operationParameter, typeDescription);
            }
            else
            {
                operationParameter = _settings.SchemaGenerator.Generate <OpenApiParameter>(contextualParameter, _schemaResolver);
                _settings.SchemaGenerator.ApplyDataAnnotations(operationParameter, typeDescription);
            }

            if (typeDescription.Type.HasFlag(JsonObjectType.Array))
            {
                operationParameter.CollectionFormat = OpenApiParameterCollectionFormat.Multi;
            }

            return(operationParameter);
        }
コード例 #8
0
        public static PropertyDeclarationSyntax CreateAuto(OpenApiParameter parameter, bool useNullableReferenceTypes)
        {
            if (parameter == null)
            {
                throw new ArgumentNullException(nameof(parameter));
            }

            if (parameter.In == ParameterLocation.Path)
            {
                useNullableReferenceTypes = false;
            }
            else if (parameter.Schema.Default != null &&
                     (parameter.In == ParameterLocation.Query ||
                      parameter.In == ParameterLocation.Header))
            {
                useNullableReferenceTypes = false;
            }

            var propertyDeclaration = CreateAuto(
                parameter.In,
                parameter.Schema.Nullable,
                parameter.Required,
                parameter.Schema.GetDataType(),
                parameter.Name.EnsureFirstCharacterToUpper(),
                useNullableReferenceTypes,
                parameter.Schema.Default);

            propertyDeclaration = parameter.In switch
            {
                ParameterLocation.Header => propertyDeclaration.AddFromHeaderAttribute(parameter.Name, parameter.Schema),
                ParameterLocation.Path => propertyDeclaration.AddFromRouteAttribute(parameter.Name, parameter.Schema),
                ParameterLocation.Query => propertyDeclaration.AddFromQueryAttribute(parameter.Name, parameter.Schema),
                _ => throw new NotImplementedException("ParameterLocation: " + nameof(ParameterLocation) + " " + parameter.In)
            };

            if (parameter.Required)
            {
                propertyDeclaration = propertyDeclaration.AddValidationAttribute(new RequiredAttribute());
            }

            return(propertyDeclaration);
        }
コード例 #9
0
        /// <summary>
        /// Sets the custom parameters.
        /// </summary>
        /// <param name="operation">The OpenApi operation.</param>
        /// <param name="customParameters">The custom parameters.</param>
        /// <param name="location">The parameter location.</param>
        protected static void AppendCustomParameters(OpenApiOperation operation, IList <CustomParameter> customParameters, ParameterLocation location)
        {
            foreach (var param in customParameters)
            {
                OpenApiParameter parameter = new OpenApiParameter
                {
                    In          = location,
                    Name        = param.Name,
                    Description = param.Description,
                    Schema      = new OpenApiSchema
                    {
                        Type = "string"
                    },
                    Required = param.Required ?? false
                };

                if (param.DocumentationURL != null)
                {
                    parameter.Example = new OpenApiString(param.DocumentationURL ?? "N/A");
                }

                if (param.ExampleValues != null)
                {
                    parameter.Examples = new Dictionary <string, OpenApiExample>();
                    int index = 1;
                    foreach (var example in param.ExampleValues)
                    {
                        OpenApiExample ex = new OpenApiExample
                        {
                            Description = example.Description
                        };

                        // maybe call convert to Uri literal
                        ex.Value = new OpenApiString(example.Value.ToString());

                        parameter.Examples.Add("example-" + index++, ex);
                    }
                }

                AppendParameter(operation, parameter);
            }
        }
コード例 #10
0
        /// <summary>Initializes a new instance of the <see cref="ParameterModelBase" /> class.</summary>
        /// <param name="parameterName">Name of the parameter.</param>
        /// <param name="variableName">Name of the variable.</param>
        /// <param name="typeName">The type name.</param>
        /// <param name="parameter">The parameter.</param>
        /// <param name="allParameters">All parameters.</param>
        /// <param name="settings">The settings.</param>
        /// <param name="generator">The client generator base.</param>
        /// <param name="typeResolver">The type resolver.</param>
        protected ParameterModelBase(string parameterName, string variableName, string typeName,
                                     OpenApiParameter parameter, IList <OpenApiParameter> allParameters, CodeGeneratorSettingsBase settings,
                                     IClientGenerator generator, TypeResolverBase typeResolver)
        {
            _allParameters = allParameters;
            _parameter     = parameter;
            _settings      = settings;
            _generator     = generator;
            _typeResolver  = typeResolver;

            Type         = typeName;
            Name         = parameterName;
            VariableName = variableName;

            var propertyNameGenerator = settings?.PropertyNameGenerator ?? throw new InvalidOperationException("PropertyNameGenerator not set.");

            _properties = _parameter.ActualSchema.ActualProperties
                          .Select(p => new PropertyModel(p.Key, p.Value, propertyNameGenerator.Generate(p.Value)))
                          .ToList();
        }
コード例 #11
0
        public void OpenApiParameterComparerShouldSucceed(
            string testCaseName,
            OpenApiParameter source,
            OpenApiParameter target,
            List <OpenApiDifference> expectedDifferences)
        {
            _output.WriteLine(testCaseName);

            var comparisonContext = new ComparisonContext(new OpenApiComparerFactory(), _sourceDocument,
                                                          _targetDocument);
            var comparer = new OpenApiParameterComparer();

            comparer.Compare(source, target, comparisonContext);

            var differences = comparisonContext.OpenApiDifferences.ToList();

            differences.Count().ShouldBeEquivalentTo(expectedDifferences.Count);

            differences.ShouldBeEquivalentTo(expectedDifferences);
        }
コード例 #12
0
        public void Apply_SetsDescriptionAndExample_FromUnderlyingGenericTypeActionParamTag()
        {
            var parameter = new OpenApiParameter {
                Schema = new OpenApiSchema {
                    Type = "string"
                }
            };
            var parameterInfo = typeof(FakeConstructedControllerWithXmlComments)
                                .GetMethod(nameof(FakeConstructedControllerWithXmlComments.ActionWithParamTags))
                                .GetParameters()[0];
            var apiParameterDescription = new ApiParameterDescription {
            };
            var filterContext           = new ParameterFilterContext(apiParameterDescription, null, null, parameterInfo: parameterInfo);

            Subject().Apply(parameter, filterContext);

            Assert.Equal("Description for param1", parameter.Description);
            Assert.NotNull(parameter.Example);
            Assert.Equal("\"Example for param1\"", parameter.Example.ToJson());
        }
コード例 #13
0
        public void Apply(OpenApiParameter parameter, ParameterFilterContext context)
        {
            if (context.ApiParameterDescription.Type == null)
            {
                return;
            }

            var type = Nullable.GetUnderlyingType(context.ApiParameterDescription.Type) ?? context.ApiParameterDescription.Type;

            if (type.IsEnum)
            {
                AddEnumParamSpec(parameter, type, context);
                parameter.Required = type == context.ApiParameterDescription.Type;
            }
            else if (type.IsArray || (type.IsGenericType && type.GetInterfaces().Contains(typeof(IEnumerable))))
            {
                var itemType = type.GetElementType() ?? type.GenericTypeArguments.First();
                AddEnumSpec(parameter, itemType, context);
            }
        }
コード例 #14
0
        public static OpenApiParameter LoadParameter(ParseNode node)
        {
            var mapNode = node.CheckMapNode("parameter");

            var pointer = mapNode.GetReferencePointer();

            if (pointer != null)
            {
                return(mapNode.GetReferencedObject <OpenApiParameter>(ReferenceType.Parameter, pointer));
            }

            var parameter = new OpenApiParameter();
            var required  = new List <string> {
                "name", "in"
            };

            ParseMap(mapNode, parameter, _parameterFixedFields, _parameterPatternFields);

            return(parameter);
        }
コード例 #15
0
        private void BuildPageableParameters(ParameterInfo parameterInfo, OpenApiOperation operation)
        {
            var parameter = operation.Parameters.Single(p => p.Name == parameterInfo.Name);

            operation.Parameters.Remove(parameter);
            parameter = new OpenApiParameter
            {
                In     = ParameterLocation.Query,
                Name   = _options.Value.JsonSerializerOptions.PropertyNamingPolicy.ConvertName(_settings.PageNumberField),
                Schema = new OpenApiSchema()
                {
                    Type = "number", Default = new OpenApiInteger(0), Description = "Page number"
                }
            };
            operation.Parameters.Add(parameter);

            parameter = new OpenApiParameter
            {
                In     = ParameterLocation.Query,
                Name   = _options.Value.JsonSerializerOptions.PropertyNamingPolicy.ConvertName(_settings.PageSizeField),
                Schema = new OpenApiSchema()
                {
                    Type = "number", Default = new OpenApiInteger(_settings.PageSize), Description = "Page size"
                }
            };
            operation.Parameters.Add(parameter);

            parameter = new OpenApiParameter
            {
                In     = ParameterLocation.Query,
                Name   = _options.Value.JsonSerializerOptions.PropertyNamingPolicy.ConvertName(_settings.SortField),
                Schema = new OpenApiSchema()
                {
                    Type = "array", Items = new OpenApiSchema()
                    {
                        Type = "string", Description = "Sort"
                    }
                }
            };
            operation.Parameters.Add(parameter);
        }
コード例 #16
0
        public bool Process(OperationProcessorContext context)
        {
            var parameterInfos = context.MethodInfo.GetParameters();
            var parameterInfo  = parameterInfos.SingleOrDefault();

            if (parameterInfo == null)
            {
                return(false);
            }

            var isQuery = context.MethodInfo.DeclaringType.IsAssignableToGenericType(typeof(IQueryRequestHandler <,>));

            if (isQuery)
            {
                // Query
                foreach (var contextualProperty in parameterInfo.ToContextualParameter().Type.GetContextualProperties())
                {
                    var operationParameter = context.DocumentGenerator.CreatePrimitiveParameter(contextualProperty.Name, contextualProperty.Name,
                                                                                                contextualProperty);

                    operationParameter.Kind = OpenApiParameterKind.Query;
                    context.OperationDescription.Operation.Parameters.Add(operationParameter);
                }
            }
            else
            {
                // Command
                var operationParameter = new OpenApiParameter
                {
                    Kind        = OpenApiParameterKind.Body,
                    Name        = parameterInfo.Name,
                    Description = parameterInfo.Name,
                    Schema      = context.SchemaGenerator.GenerateWithReferenceAndNullability <JsonSchema>(parameterInfo.ParameterType.ToContextualType(), true, context.SchemaResolver),
                    Position    = 1
                };

                context.OperationDescription.Operation.Parameters.Add(operationParameter);
                ((Dictionary <ParameterInfo, OpenApiParameter>)context.Parameters)[parameterInfo] = operationParameter;
            }
            return(true);
        }
コード例 #17
0
        /// <summary>Resolves the type of the parameter.</summary>
        /// <param name="parameter">The parameter.</param>
        /// <returns>The parameter type name.</returns>
        protected override string ResolveParameterType(OpenApiParameter parameter)
        {
            var schema = parameter.ActualSchema;

            if (parameter.IsBinaryBodyParameter)
            {
                if (_settings is CSharpControllerGeneratorSettings controllerSettings)
                {
                    if (schema.Type == JsonObjectType.Array && schema.Item.IsBinary)
                    {
                        return(controllerSettings.ControllerTarget == CSharpControllerTarget.AspNetCore ?
                               "System.Collections.Generic.ICollection<Microsoft.AspNetCore.Http.IFormFile>" :
                               "System.Collections.Generic.ICollection<System.Web.HttpPostedFileBase>");
                    }
                    else
                    {
                        return(controllerSettings.ControllerTarget == CSharpControllerTarget.AspNetCore ?
                               "Microsoft.AspNetCore.Http.IFormFile" :
                               "System.Web.HttpPostedFileBase");
                    }
                }
                else
                {
                    return("System.IO.Stream");
                }
            }

            if (schema.IsBinary)
            {
                if (parameter.CollectionFormat == OpenApiParameterCollectionFormat.Multi && !schema.Type.HasFlag(JsonObjectType.Array))
                {
                    return("System.Collections.Generic.IEnumerable<FileParameter>");
                }

                return("FileParameter");
            }

            return(base.ResolveParameterType(parameter)
                   .Replace(_settings.CSharpGeneratorSettings.ArrayType + "<", _settings.ParameterArrayType + "<")
                   .Replace(_settings.CSharpGeneratorSettings.DictionaryType + "<", _settings.ParameterDictionaryType + "<"));
        }
コード例 #18
0
        public static OpenApiParameter LoadParameter(ParseNode node, bool loadRequestBody)
        {
            // Reset the local variables every time this method is called.
            _isBodyOrFormData = false;

            var mapNode = node.CheckMapNode("parameter");

            var pointer = mapNode.GetReferencePointer();

            if (pointer != null)
            {
                return(mapNode.GetReferencedObject <OpenApiParameter>(ReferenceType.Parameter, pointer));
            }

            var parameter = new OpenApiParameter();

            ParseMap(mapNode, parameter, _parameterFixedFields, _parameterPatternFields);

            ProcessAnyFields(mapNode, parameter, _parameterAnyFields);
            ProcessAnyListFields(mapNode, parameter, _parameterAnyListFields);

            var schema = node.Context.GetFromTempStorage <OpenApiSchema>("schema");

            if (schema != null)
            {
                parameter.Schema = schema;
                node.Context.SetTempStorage("schema", null);
            }

            if (_isBodyOrFormData && !loadRequestBody)
            {
                return(null); // Don't include Form or Body parameters when normal parameters are loaded.
            }

            if (loadRequestBody && !_isBodyOrFormData)
            {
                return(null); // Don't include non-Body or non-Form parameters when request bodies are loaded.
            }

            return(parameter);
        }
コード例 #19
0
        /// <summary>Generates the parameter name for the given parameter.</summary>
        /// <param name="parameter">The parameter.</param>
        /// <param name="allParameters">All parameters.</param>
        /// <returns>The parameter name.</returns>
        public string Generate(OpenApiParameter parameter, IEnumerable <OpenApiParameter> allParameters)
        {
            if (string.IsNullOrEmpty(parameter.Name))
            {
                return("unnamed");
            }

            var variableName = ConversionUtilities.ConvertToLowerCamelCase(parameter.Name
                                                                           .Replace("-", "_")
                                                                           .Replace(".", "_")
                                                                           .Replace("$", string.Empty)
                                                                           .Replace("[", string.Empty)
                                                                           .Replace("]", string.Empty), true);

            if (allParameters.Count(p => p.Name == parameter.Name) > 1)
            {
                return(variableName + parameter.Kind);
            }

            return(variableName);
        }
コード例 #20
0
        private void ApplySwaggerParameterAttribute(OpenApiParameter parameter, IEnumerable <object> customAttributes)
        {
            var swaggerParameterAttribute = customAttributes
                                            .OfType <SwaggerParameterAttribute>()
                                            .FirstOrDefault();

            if (swaggerParameterAttribute == null)
            {
                return;
            }

            if (swaggerParameterAttribute.Description != null)
            {
                parameter.Description = swaggerParameterAttribute.Description;
            }

            if (swaggerParameterAttribute.RequiredProvided)
            {
                parameter.Required = swaggerParameterAttribute.Required;
            }
        }
コード例 #21
0
        /// <summary>Resolves the type of the parameter.</summary>
        /// <param name="parameter">The parameter.</param>
        /// <returns>The parameter type name.</returns>
        protected override string ResolveParameterType(OpenApiParameter parameter)
        {
            if (parameter.IsBinaryBodyParameter)
            {
                return("Blob");
            }

            var schema = parameter.ActualSchema;

            if (schema.IsBinary)
            {
                if (parameter.CollectionFormat == OpenApiParameterCollectionFormat.Multi && !schema.Type.HasFlag(JsonObjectType.Array))
                {
                    return("FileParameter[]");
                }

                return("FileParameter");
            }

            return(base.ResolveParameterType(parameter));
        }
 private static string PropertyValueGenerator(
     OpenApiParameter parameter,
     IDictionary <string, OpenApiSchema> componentsSchemas,
     bool useForBadRequest,
     string?customValue)
 {
     // Match on OpenApiSchemaExtensions->GetDataType
     return(parameter.Schema.GetDataType() switch
     {
         "double" => ValueTypeTestPropertiesHelper.Number(parameter.Name, parameter.Schema, useForBadRequest),
         "long" => ValueTypeTestPropertiesHelper.Number(parameter.Name, parameter.Schema, useForBadRequest),
         "int" => ValueTypeTestPropertiesHelper.Number(parameter.Name, parameter.Schema, useForBadRequest),
         "bool" => ValueTypeTestPropertiesHelper.CreateValueBool(useForBadRequest),
         "string" => ValueTypeTestPropertiesHelper.CreateValueString(parameter.Name, parameter.Schema, parameter.In, useForBadRequest, 0, customValue),
         "DateTimeOffset" => ValueTypeTestPropertiesHelper.CreateValueDateTimeOffset(useForBadRequest),
         "Guid" => ValueTypeTestPropertiesHelper.CreateValueGuid(useForBadRequest),
         "Uri" => ValueTypeTestPropertiesHelper.CreateValueUri(useForBadRequest),
         "Email" => ValueTypeTestPropertiesHelper.CreateValueEmail(useForBadRequest),
         "Array" when parameter.In == ParameterLocation.Query => ValueTypeTestPropertiesHelper.CreateValueArray(parameter.Name, parameter.Schema.Items, parameter.In, useForBadRequest, 3),
         _ => PropertyValueGeneratorTypeResolver(parameter, componentsSchemas, useForBadRequest)
     });
コード例 #23
0
ファイル: OperationModelBase.cs プロジェクト: zhutoutou/NSwag
        /// <summary>Resolves the type of the parameter.</summary>
        /// <param name="parameter">The parameter.</param>
        /// <returns>The parameter type name.</returns>
        protected virtual string ResolveParameterType(OpenApiParameter parameter)
        {
            var schema = parameter.ActualSchema;

            if (parameter.IsXmlBodyParameter)
            {
                return("string");
            }

            if (parameter.CollectionFormat == OpenApiParameterCollectionFormat.Multi && !schema.Type.HasFlag(JsonObjectType.Array))
            {
                schema = new JsonSchema {
                    Type = JsonObjectType.Array, Item = schema
                };
            }

            var typeNameHint = !schema.HasTypeNameTitle ? ConversionUtilities.ConvertToUpperCamelCase(parameter.Name, true) : null;
            var isNullable   = parameter.IsRequired == false || parameter.IsNullable(_settings.CodeGeneratorSettings.SchemaType);

            return(_resolver.Resolve(schema, isNullable, typeNameHint));
        }
コード例 #24
0
        private static IList <OpenApiParameter> BuildParametersList(MethodDescriptor descriptor, string httpPath,
                                                                    OperationType operationType)
        {
            var addOnlyPathParams = operationType != OperationType.Get;
            var parametersType    = descriptor.InputType.ClrType;
            var result            = new List <OpenApiParameter>();

            foreach (var property in parametersType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                var isPathParam = httpPath.Contains($"{{{ToCamelCase(property.Name)}}}");

                if (addOnlyPathParams && false == isPathParam)
                {
                    continue;
                }

                var parameter = new OpenApiParameter
                {
                    In   = isPathParam ? ParameterLocation.Path : ParameterLocation.Query,
                    Name = ToCamelCase(property.Name)
                };
                var propertyType = property.PropertyType;
                if (_primitiveTypeMap.ContainsKey(propertyType))
                {
                    parameter.Schema = _primitiveTypeMap[propertyType]();
                }
                else if (propertyType.IsEnum)
                {
                    parameter.Schema = CreateEnumSchema(propertyType);
                }
                else
                {
                    throw new InvalidOperationException("Unknown parameter type");
                }

                result.Add(parameter);
            }

            return(result.Any() ? result : null);
        }
コード例 #25
0
 /// <inheritdoc/>
 public void Apply(OpenApiParameter parameter, ParameterFilterContext context)
 {
     //
     // fix current bug where properties are not added correctly
     // Lookup property schema in schema repo
     //
     if (context.PropertyInfo != null)
     {
         // Query was passed a parameter with properties
         var propertySchema = context.SchemaRepository.Schemas
                              .Where(p => p.Key.EqualsIgnoreCase(context.ParameterInfo.ParameterType.Name))
                              .SelectMany(p => p.Value.Properties)
                              .Where(p => p.Key.EqualsIgnoreCase(context.PropertyInfo.Name))
                              .FirstOrDefault();
         if (propertySchema.Value != null)
         {
             propertySchema.Value.Description =
                 propertySchema.Value.Description.SingleSpacesNoLineBreak();
             // Replace parameter definition with property schema
             parameter.Name = propertySchema.Key;
             // Quick and dirty clone of the schema for the parameter
             parameter.Schema = JsonConvert.DeserializeObject <OpenApiSchema>(
                 JsonConvert.SerializeObject(propertySchema.Value));
         }
         parameter.Required = context.PropertyInfo
                              .GetCustomAttributes(typeof(RequiredAttribute), true)
                              .Any();
         AdjustSchema(context.PropertyInfo.PropertyType, parameter.Schema);
     }
     else if (context.ParameterInfo != null)
     {
         // Query was passed a parameter with properties
         AdjustSchema(context.ParameterInfo.ParameterType, parameter.Schema);
     }
     if (parameter.Schema != null)
     {
         parameter.Schema.Description = parameter.Schema.Description.SingleSpacesNoLineBreak();
     }
     parameter.Description = parameter.Description.SingleSpacesNoLineBreak();
 }
コード例 #26
0
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            OpenApiParameter apiVersionParameter = operation.Parameters.SingleOrDefault(p => p.Name == ApiVersionQueryParameter);

            if (apiVersionParameter == null)
            {
                return;
            }

            ApiVersionAttribute attribute = context?.MethodInfo?.DeclaringType?
                                            .GetCustomAttributes(typeof(ApiVersionAttribute), false)
                                            .Cast <ApiVersionAttribute>()
                                            .SingleOrDefault();

            string version = attribute?.Versions?.SingleOrDefault()?.ToString();

            if (version != null)
            {
                apiVersionParameter.Example        = new OpenApiString(version);
                apiVersionParameter.Schema.Example = new OpenApiString(version);
            }
        }
コード例 #27
0
        private OpenApiParameter CreatePrimitiveOpenApiParameter(ContextualType contextualParameter, JsonTypeDescription typeDescription)
        {
            OpenApiParameter operationParameter;

            if (typeDescription.RequiresSchemaReference(_settings.TypeMappers))
            {
                operationParameter        = new OpenApiParameter();
                operationParameter.Schema = new JsonSchema();

                _settings.SchemaGenerator.ApplyDataAnnotations(operationParameter.Schema, typeDescription);

                var referencedSchema = _settings.SchemaGenerator.Generate(contextualParameter, _schemaResolver);

                var hasSchemaAnnotations = JsonConvert.SerializeObject(operationParameter.Schema) != "{}";
                if (hasSchemaAnnotations || typeDescription.IsNullable)
                {
                    operationParameter.Schema.IsNullableRaw = true;
                    operationParameter.Schema.OneOf.Add(new JsonSchema {
                        Reference = referencedSchema.ActualSchema
                    });
                }
                else
                {
                    operationParameter.Schema = new JsonSchema {
                        Reference = referencedSchema.ActualSchema
                    };
                }
            }
            else
            {
                operationParameter        = new OpenApiParameter();
                operationParameter.Schema = _settings.SchemaGenerator.GenerateWithReferenceAndNullability <JsonSchema>(
                    contextualParameter, typeDescription.IsNullable, _schemaResolver);

                _settings.SchemaGenerator.ApplyDataAnnotations(operationParameter.Schema, typeDescription);
            }

            return(operationParameter);
        }
コード例 #28
0
 public void Traverse(OpenApiParameter parameter)
 {
     if (parameter == null)
     {
         return;
     }
     Visitor.Visit(parameter);
     if (parameter.Content != null)
     {
         foreach (var mediaType in parameter.Content)
         {
             Traverse(mediaType.Value);
         }
     }
     if (parameter.Examples != null)
     {
         foreach (var example in parameter.Examples)
         {
             Traverse(example.Value);
         }
     }
 }
コード例 #29
0
        private void ApplyParamTags(OpenApiParameter parameter, ParameterFilterContext context)
        {
            if (!(context.ParameterInfo.Member is MethodInfo methodInfo))
            {
                return;
            }

            // If method is from a constructed generic type, look for comments from the generic type method
            var targetMethod = methodInfo.DeclaringType.IsConstructedGenericType
                ? methodInfo.GetUnderlyingGenericTypeMethod()
                : methodInfo;

            if (targetMethod == null)
            {
                return;
            }

            var methodMemberName = XmlCommentsNodeNameHelper.GetMemberNameForMethod(targetMethod);
            var paramNode        = _xmlNavigator.SelectSingleNode(
                $"/doc/members/member[@name='{methodMemberName}']/param[@name='{context.ParameterInfo.Name}']");

            if (paramNode != null)
            {
                parameter.Description = XmlCommentsTextHelper.Humanize(paramNode.InnerXml);

                var example = paramNode.GetAttribute("example", "");
                if (string.IsNullOrEmpty(example))
                {
                    return;
                }

                var exampleAsJson = (parameter.Schema?.ResolveType(context.SchemaRepository) == "string")
                    ? $"\"{example}\""
                    : example;

                parameter.Example = OpenApiAnyFactory.CreateFromJson(exampleAsJson);
            }
        }
コード例 #30
0
        public void ValidateExampleShouldNotHaveDataTypeMismatchForSimpleSchema()
        {
            // Arrange
            IEnumerable <OpenApiError> errors;
            var parameter = new OpenApiParameter()
            {
                Name     = "parameter1",
                In       = ParameterLocation.Path,
                Required = true,
                Example  = new OpenApiInteger(55),
                Schema   = new OpenApiSchema()
                {
                    Type = "string",
                }
            };

            // Act
            var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet());

            validator.Enter("{parameter1}");
            var walker = new OpenApiWalker(validator);

            walker.Walk(parameter);

            errors = validator.Errors;
            bool result = !errors.Any();

            // Assert
            result.Should().BeFalse();
            errors.Select(e => e.Message).Should().BeEquivalentTo(new[]
            {
                RuleHelpers.DataTypeMismatchedErrorMessage
            });
            errors.Select(e => e.Pointer).Should().BeEquivalentTo(new[]
            {
                "#/{parameter1}/example",
            });
        }