コード例 #1
0
        private IParameter CreateBodyParameter(
            ApiParameterDescription apiParameterDescription,
            string name,
            bool isRequired,
            ISchemaRegistry schemaRegistry)
        {
            var schema = schemaRegistry.GetOrRegister(apiParameterDescription.Type);

            return(new BodyParameter {
                Name = name, Schema = schema, Required = isRequired
            });
        }
コード例 #2
0
        private static void AddEnumParmSpec(Dictionary <string, object> extensions, Type type, ISchemaRegistry schemaRegistry)
        {
            var registeredType = schemaRegistry.GetOrRegister(type);

            if (registeredType.Ref == null)
            {
                return;
            }

            extensions.Add("x-schema", registeredType);
            extensions.Add("x-enumNames", Enum.GetNames(type));
        }
コード例 #3
0
ファイル: SwaggerGenerator.cs プロジェクト: zzskyhot/surging
        private IParameter CreateNonBodyParameter(ServiceEntry serviceEntry, ParameterInfo parameterInfo, ISchemaRegistry schemaRegistry)
        {
            string reg          = @"(?<={)[^{}]*(?=})";
            var    nonBodyParam = new NonBodyParameter
            {
                Name     = parameterInfo.Name,
                In       = "query",
                Required = true,
            };

            if (Regex.IsMatch(serviceEntry.RoutePath, reg) && GetParameters(serviceEntry.RoutePath).Contains(parameterInfo.Name))
            {
                nonBodyParam.In = "path";
            }

            if (parameterInfo.ParameterType == null)
            {
                nonBodyParam.Type = "string";
            }
            else if (typeof(IEnumerable <KeyValuePair <string, StringValues> >).IsAssignableFrom(parameterInfo.ParameterType) &&
                     parameterInfo.ParameterType.Name == "HttpFormCollection")
            {
                nonBodyParam.Type = "file";
                nonBodyParam.In   = "formData";
            }
            else
            {
                // Retrieve a Schema object for the type and copy common fields onto the parameter
                var schema = schemaRegistry.GetOrRegister(parameterInfo.ParameterType);

                // NOTE: While this approach enables re-use of SchemaRegistry logic, it introduces complexity
                // and constraints elsewhere (see below) and needs to be refactored!

                if (schema.Ref != null)
                {
                    // The registry created a referenced Schema that needs to be located. This means it's not neccessarily
                    // exclusive to this parameter and so, we can't assign any parameter specific attributes or metadata.
                    schema = schemaRegistry.Definitions[schema.Ref.Replace("#/definitions/", string.Empty)];
                }
                else
                {
                    // It's a value Schema. This means it's exclusive to this parameter and so, we can assign
                    // parameter specific attributes and metadata. Yep - it's hacky!
                    schema.Default = (parameterInfo != null && parameterInfo.IsOptional)
                        ? parameterInfo.DefaultValue
                        : null;
                }

                nonBodyParam.PopulateFrom(schema);
            }
            return(nonBodyParam);
        }
コード例 #4
0
        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);
        }
コード例 #5
0
        private IParameter CreateParameter(
            ApiDescription apiDescription,
            ApiParameterDescription paramDescription,
            ISchemaRegistry schemaRegistry)
        {
            var location = GetParameterLocation(apiDescription, paramDescription);

            var name = _settings.DescribeAllParametersInCamelCase
                ? paramDescription.Name.ToCamelCase()
                : paramDescription.Name;

            var schema = (paramDescription.Type == null) ? null : schemaRegistry.GetOrRegister(paramDescription.Type);

            if (location == "body")
            {
                return(new BodyParameter
                {
                    Name = name,
                    Schema = schema
                });
            }

            var nonBodyParam = new NonBodyParameter
            {
                Name     = name,
                In       = location,
                Required = (location == "path") || paramDescription.IsRequired()
            };

            if (schema == null)
            {
                nonBodyParam.Type = "string";
            }
            else
            {
                // In some cases (e.g. enum types), the schemaRegistry may return a reference instead of a
                // full schema. Retrieve the full schema before populating the parameter description
                var fullSchema = (schema.Ref != null)
                    ? schemaRegistry.Definitions[schema.Ref.Replace("#/definitions/", string.Empty)]
                    : schema;

                nonBodyParam.PopulateFrom(schema);
            }

            if (nonBodyParam.Type == "array")
            {
                nonBodyParam.CollectionFormat = "multi";
            }

            return(nonBodyParam);
        }
コード例 #6
0
        private Response CreateResponse(ServiceEntry apiResponseType, MethodInfo methodInfo, ISchemaRegistry schemaRegistry)
        {
            var description = ResponseDescriptionMap
                              .FirstOrDefault((entry) => Regex.IsMatch("200", entry.Key))
                              .Value;

            return(new Response
            {
                Description = description,
                Schema = (methodInfo.ReturnType != typeof(Task) && methodInfo.ReturnType != typeof(void))
                    ? schemaRegistry.GetOrRegister(typeof(HttpResultMessage <>).MakeGenericType(methodInfo.ReturnType.GenericTypeArguments))
                    : null
            });
        }
コード例 #7
0
        private Response CreateResponse(ApiResponseType apiResponseType, ISchemaRegistry schemaRegistry)
        {
            var description = ResponseDescriptionMap
                              .FirstOrDefault((entry) => Regex.IsMatch(apiResponseType.StatusCode.ToString(), entry.Key))
                              .Value;

            return(new Response
            {
                Description = description,
                Schema = (apiResponseType.Type != null && apiResponseType.Type != typeof(void))
                    ? schemaRegistry.GetOrRegister(apiResponseType.Type)
                    : null
            });
        }
コード例 #8
0
        public void SetRequestExampleForType(
            Operation operation,
            ISchemaRegistry schemaRegistry,
            Type requestType,
            object example,
            IContractResolver contractResolver = null,
            JsonConverter jsonConverter        = null)
        {
            if (example == null)
            {
                return;
            }

            var schema = schemaRegistry.GetOrRegister(requestType);

            var bodyParameters = operation.Parameters.Where(p => p.In == "body").Cast <BodyParameter>();
            var bodyParameter  = bodyParameters.FirstOrDefault(p => p?.Schema.Ref == schema.Ref || p.Schema?.Items?.Ref == schema.Ref);

            if (bodyParameter == null)
            {
                return; // The type in their [SwaggerRequestExample(typeof(requestType), ...] is not passed to their controller action method
            }

            var serializerSettings = serializerSettingsDuplicator.SerializerSettings(contractResolver, jsonConverter);

            var formattedExample = jsonFormatter.FormatJson(example, serializerSettings, includeMediaType: false);

            string name = SchemaDefinitionName(requestType, schema);

            if (string.IsNullOrEmpty(name))
            {
                return;
            }

            // set the example on the object in the schema registry (this is what swagger-ui will display)
            if (schemaRegistry.Definitions.ContainsKey(name))
            {
                var definitionToUpdate = schemaRegistry.Definitions[name];
                if (definitionToUpdate.Example == null)
                {
                    definitionToUpdate.Example = formattedExample;
                }
            }
            else
            {
                bodyParameter.Schema.Example = formattedExample; // set example on the request paths/parameters/schema/example property
            }
        }
コード例 #9
0
        private void ApplyResponsesFrom(
            Operation operation,
            IOrderedEnumerable<SwaggerResponseAttribute> attributes,
            ISchemaRegistry schemaRegistry)
        {
            foreach (var attr in attributes)
            {
                var statusCode = attr.StatusCode.ToString();

                operation.Responses[statusCode] = new Response
                {
                    Description = attr.Description ?? InferDescriptionFrom(statusCode),
                    Schema = (attr.Type != null) ? schemaRegistry.GetOrRegister(attr.Type) : null
                };
            }
        }
コード例 #10
0
        private void ApplyResponsesFrom(
            Operation operation,
            IOrderedEnumerable <SwaggerResponseAttribute> attributes,
            ISchemaRegistry schemaRegistry)
        {
            foreach (var attr in attributes)
            {
                var statusCode = attr.StatusCode.ToString();

                operation.Responses[statusCode] = new Response
                {
                    Description = attr.Description ?? InferDescriptionFrom(statusCode),
                    Schema      = (attr.Type != null) ? schemaRegistry.GetOrRegister(attr.Type) : null
                };
            }
        }
コード例 #11
0
        private IParameter CreateParameter(
            ApiDescription apiDescription,
            ApiParameterDescription paramDescription,
            ISchemaRegistry schemaRegistry)
        {
            var location = GetParameterLocation(apiDescription, paramDescription);

            var name = _settings.DescribeAllParametersInCamelCase
                ? paramDescription.Name.ToCamelCase()
                : paramDescription.Name;

            var schema = (paramDescription.Type == null) ? null : schemaRegistry.GetOrRegister(paramDescription.Type);

            if (location == "body")
            {
                return(new BodyParameter
                {
                    Name = name,
                    Schema = schema
                });
            }

            var nonBodyParam = new NonBodyParameter
            {
                Name     = name,
                In       = location,
                Required = (location == "path")
            };

            if (schema == null)
            {
                nonBodyParam.Type = "string";
            }
            else
            {
                nonBodyParam.PopulateFrom(schema);
            }

            if (nonBodyParam.Type == "array")
            {
                nonBodyParam.CollectionFormat = "multi";
            }

            return(nonBodyParam);
        }
コード例 #12
0
        /// <summary>
        /// 创建接口参数
        /// </summary>
        /// <param name="pams"></param>
        /// <param name="schemaRegistry"></param>
        /// <returns></returns>
        public IParameter CreateParamters(ControllerParameterDescriptor pams, ISchemaRegistry schemaRegistry)
        {
            var location = GetParameterLocation(pams);

            var schema = (pams.ParameterType == null) ? null : schemaRegistry.GetOrRegister(pams.ParameterType);

            if (location == "body")
            {
                return(new BodyParameter
                {
                    Name = pams.Name,
                    Description = pams.Name,
                    Schema = schema
                });
            }

            if (location != "header" && location != "query")
            {
                location = "path";
            }

            var nonBodyParam = new NonBodyParameter
            {
                Name     = pams.Name,
                In       = location,
                Required = (location == "path"),
            };

            if (schema == null)
            {
                nonBodyParam.Type = "string";
            }
            else
            {
                nonBodyParam.PopulateFrom(schema);
            }

            if (nonBodyParam.Type == "array")
            {
                nonBodyParam.CollectionFormat = "multi";
            }

            return(nonBodyParam);
        }
        private static void SetRequestModelExamples(Operation operation, ISchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var actionAttributes         = apiDescription.ActionAttributes();
            var swaggerRequestAttributes = actionAttributes.Where(r => r.GetType() == typeof(SwaggerRequestExampleAttribute));

            foreach (var attribute in swaggerRequestAttributes)
            {
                var attr   = (SwaggerRequestExampleAttribute)attribute;
                var schema = schemaRegistry.GetOrRegister(attr.RequestType);

                var request = operation.Parameters.FirstOrDefault(p => p.In == "body" /* && p.schema.@ref == schema.@ref */);

                if (request != null)
                {
                    var provider = _services == null
                        ? (IExamplesProvider)Activator.CreateInstance(attr.ExamplesProviderType)
                        : (IExamplesProvider)_services.GetService(attr.ExamplesProviderType)
                                   ?? (IExamplesProvider)Activator.CreateInstance(attr.ExamplesProviderType);

                    var parts = schema.Ref?.Split('/');
                    if (parts == null)
                    {
                        continue;
                    }

                    var name = parts.Last();

                    var definitionToUpdate = schemaRegistry.Definitions[name];

                    if (definitionToUpdate != null)
                    {
                        var serializerSettings = new JsonSerializerSettings
                        {
                            ContractResolver  = attr.ContractResolver,
                            NullValueHandling = NullValueHandling.Ignore // ignore null values because swagger does not support null objects https://github.com/OAI/OpenAPI-Specification/issues/229
                        };

                        definitionToUpdate.Example = ((dynamic)FormatAsJson(provider, serializerSettings))["application/json"];
                    }
                }
            }
        }
コード例 #14
0
        private void RegisterType(ISchemaRegistry schemaRegistry, Type t)
        {
            var baseType = t.BaseType;

            if (baseType == null)
            {
                return;
            }

            var assemblies = new List <Assembly>()
            {
                t.Assembly
            };

            // don't include base type assembly
            // if its the same as the child type
            // or if base type is object
            if (baseType.Assembly != t.Assembly &&
                baseType != typeof(object))
            {
                assemblies.Add(baseType.Assembly);
            }

            List <Type> derivedTypes = new List <Type>();

            foreach (var assembly in assemblies)
            {
                var types = assembly
                            .GetTypes()
                            .Where(p => p.BaseType == baseType);

                derivedTypes.AddRange(types);
            }

            foreach (var dt in derivedTypes)
            {
                schemaRegistry.GetOrRegister(dt);
            }

            RegisterType(schemaRegistry, baseType);
        }
コード例 #15
0
        /// <summary>
        /// Applies the associated Swagger filter.
        /// </summary>
        /// <param name="swaggerDocument">
        /// The current Swagger document.
        /// </param>
        /// <param name="context">
        /// The current context.
        /// </param>
        public void Apply(SwaggerDocument swaggerDocument, DocumentFilterContext context)
        {
            if (context != null)
            {
                ISchemaRegistry schemaRegistry = context.SchemaRegistry;
                Schema          schema         = schemaRegistry.Definitions[_type.Name];

                schema.Discriminator = _discriminator;
                if (!schema.Properties.ContainsKey(_discriminator))
                {
                    schema.Properties.Add(_discriminator, new Schema {
                        Type = "string"
                    });
                }

                _type.Assembly.GetTypes()
                .Where(x => _type != x && _type.IsAssignableFrom(x))
                .ToList()
                .ForEach(x => schemaRegistry.GetOrRegister(x));
            }
        }
コード例 #16
0
        private IParameter CreateParameter(
            ApiDescription apiDescription,
            ApiParameterDescription apiParameterDescription,
            ISchemaRegistry schemaRegistry)
        {
            var name = _settings.DescribeAllParametersInCamelCase
                ? apiParameterDescription.Name.ToCamelCase()
                : apiParameterDescription.Name;

            var location = ParameterLocationMap.ContainsKey(apiParameterDescription.Source)
                ? ParameterLocationMap[apiParameterDescription.Source]
                : "query";

            var schema = (apiParameterDescription.Type != null)
                ? schemaRegistry.GetOrRegister(apiParameterDescription.Type)
                : null;

            var isRequired = apiParameterDescription.IsRequired();

            var controllerParameterDescriptor = GetControllerParameterDescriptorOrNull(
                apiDescription, apiParameterDescription);

            var parameter = (location == "body")
                ? new BodyParameter {
                Name = name, Schema = schema, Required = isRequired
            }
                : CreateNonBodyParameter(name, location, schema, isRequired, schemaRegistry);

            var filterContext = new ParameterFilterContext(
                apiParameterDescription,
                controllerParameterDescriptor,
                schemaRegistry);

            foreach (var filter in _settings.ParameterFilters)
            {
                filter.Apply(parameter, filterContext);
            }

            return(parameter);
        }
コード例 #17
0
        private IParameter CreateParameter(ApiParameterDescription paramDesc, ISchemaRegistry schemaRegistry)
        {
            var source = paramDesc.Source.Id.ToLower();
            var schema = (paramDesc.Type == null) ? null : schemaRegistry.GetOrRegister(paramDesc.Type);

            if (source == "body")
            {
                return(new BodyParameter
                {
                    Name = paramDesc.Name,
                    In = source,
                    Schema = schema
                });
            }
            else
            {
                var nonBodyParam = new NonBodyParameter
                {
                    Name     = paramDesc.Name,
                    In       = source,
                    Required = (source == "path")
                };

                if (schema == null)
                {
                    nonBodyParam.Type = "string";
                }
                else
                {
                    nonBodyParam.PopulateFrom(schema);
                }

                if (nonBodyParam.Type == "array")
                {
                    nonBodyParam.CollectionFormat = "multi";
                }

                return(nonBodyParam);
            }
        }
コード例 #18
0
        /// <summary>
        /// 创建接口返回数据格式
        /// </summary>
        /// <param name="actionDescriptor"></param>
        /// <param name="schemaRegistry"></param>
        /// <returns></returns>
        public Dictionary <string, Response> CreateResponse(ControllerActionDescriptor actionDescriptor, ISchemaRegistry schemaRegistry)
        {
            var result       = new Dictionary <string, Response>();
            var responseType = actionDescriptor.FilterDescriptors
                               .Where(x => x.Filter is IFilterMetadata)
                               .Select(x => x.Filter).OfType <ProducesResponseTypeAttribute>()
                               .DefaultIfEmpty(new ProducesResponseTypeAttribute(200));

            foreach (var item in responseType)
            {
                var statusCode = item.StatusCode.ToString();
                var model      = new Response();

                model.Description = ResponseDescriptionMap.FirstOrDefault(x => Regex.IsMatch(statusCode, x.Key)).Value;
                model.Schema      = (item.Type != null && item.Type != typeof(void))
                    ? schemaRegistry.GetOrRegister(item.Type)
                    : null;

                result.Add(statusCode, model);
            }
            return(result);
        }
コード例 #19
0
        private OpenApiMediaType GenerateRequestMediaType(
            string contentType,
            ApiDescription apiDescription,
            ISchemaRegistry schemaRegistry)
        {
            // If there's form parameters, generate the form-flavoured media type
            var apiParametersFromForm = apiDescription.ParameterDescriptions
                                        .Where(paramDesc => paramDesc.IsFromForm());

            if (apiParametersFromForm.Any())
            {
                var schema = GenerateSchemaFromApiParameters(apiDescription, apiParametersFromForm, schemaRegistry);

                // Provide schema and corresponding encoding map to specify "form" serialization style for all properties
                // This indicates that array properties must be submitted as multiple parameters with the same name.
                // NOTE: the swagger-ui doesn't currently honor encoding metadata - https://github.com/swagger-api/swagger-ui/issues/4836

                return(new OpenApiMediaType
                {
                    Schema = schema,
                    Encoding = schema.Properties.ToDictionary(
                        entry => entry.Key,
                        entry => new OpenApiEncoding {
                        Style = ParameterStyle.Form
                    }
                        )
                });
            }

            // Otherwise, generate a regular media type
            var apiParameterFromBody = apiDescription.ParameterDescriptions
                                       .First(paramDesc => paramDesc.IsFromBody());

            return(new OpenApiMediaType
            {
                Schema = schemaRegistry.GetOrRegister(apiParameterFromBody.Type)
            });
        }
コード例 #20
0
        private static void RegisterSubClasses(ISchemaRegistry schemaRegistry, Type abstractType)
        {
            const string discriminatorName = "discriminator";

            var parentSchema = schemaRegistry.Definitions[abstractType.Name];

            //set up a discriminator property (it must be required)
            //parentSchema.Discriminator = discriminatorName;
            //parentSchema.Required = new List<string> { discriminatorName };

            //if (!parentSchema.Properties.ContainsKey(discriminatorName))
            //    parentSchema.Properties.Add(discriminatorName, new Schema { Type = "string" });

            //register all subclasses
            var derivedTypes = abstractType.Assembly
                               .GetTypes()
                               .Where(x => abstractType != x && abstractType.IsAssignableFrom(x));

            foreach (var item in derivedTypes)
            {
                schemaRegistry.GetOrRegister(item);
            }
        }
コード例 #21
0
        private OpenApiSchema GenerateSchemaFromApiParameters(
            ApiDescription apiDescription,
            IEnumerable <ApiParameterDescription> apiParameters,
            ISchemaRegistry schemaRegistry)
        {
            // First, map to a data structure that captures the pertinent metadata
            var parametersMetadata = apiParameters
                                     .Select(paramDesc =>
            {
                paramDesc.GetAdditionalMetadata(
                    apiDescription,
                    out ParameterInfo parameterInfo,
                    out PropertyInfo propertyInfo,
                    out IEnumerable <object> parameterOrPropertyAttributes);

                var name       = _options.DescribeAllParametersInCamelCase ? paramDesc.Name.ToCamelCase() : paramDesc.Name;
                var isRequired = parameterOrPropertyAttributes.Any(attr => RequiredAttributeTypes.Contains(attr.GetType()));
                var schema     = schemaRegistry.GetOrRegister(paramDesc.Type);

                return(new
                {
                    Name = name,
                    IsRequired = isRequired,
                    Schema = schema
                });
            });

            return(new OpenApiSchema
            {
                Type = "object",
                Properties = parametersMetadata.ToDictionary(
                    metadata => metadata.Name,
                    metadata => metadata.Schema
                    ),
                Required = new SortedSet <string>(parametersMetadata.Where(m => m.IsRequired).Select(m => m.Name)),
            });
        }
コード例 #22
0
        private static void SetRequestModelExamples(Operation operation, ISchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var actionAttributes = apiDescription
                                   .ActionAttributes()
                                   .OfType <SwaggerRequestExampleAttribute>();

            foreach (var attr in actionAttributes)
            {
                var schema = schemaRegistry.GetOrRegister(attr.RequestType);

                var bodyParameters = operation.Parameters.Where(p => p.In == "body").Cast <BodyParameter>();
                var request        = bodyParameters.FirstOrDefault(p => p.Schema.Ref == schema.Ref || p.Schema.Items.Ref == schema.Ref);

                if (request != null)
                {
                    var provider = ExamplesProvider(_services, attr.ExamplesProviderType);

                    // var name = attr.RequestType.Name; // this doesn't work for generic types, so need to to schema.ref split
                    var parts = schema.Ref?.Split('/');
                    if (parts == null)
                    {
                        continue;
                    }

                    var name = parts.Last();

                    if (schemaRegistry.Definitions.ContainsKey(name))
                    {
                        var definitionToUpdate = schemaRegistry.Definitions[name];
                        var serializerSettings = SerializerSettings(attr.ContractResolver, attr.JsonConverter);

                        definitionToUpdate.Example = FormatJson(provider, serializerSettings, false);
                    }
                }
            }
        }
コード例 #23
0
        //TODO: https://github.com/domaindrivendev/Ahoy/issues/234
        //public static void AddDefaultToParameter(this BodyParameter parameter, ISchemaRegistry schemaRegistry, string operationId, object @default)
        //{
        //    if (@default != null)
        //        parameter.Schema = schemaRegistry.AddDefaultToSchemaDefinitions(operationId, @default);
        //}

        private static Schema AddExampleToSchemaDefinitions(this ISchemaRegistry schemaRegistry, string operationId, object example, string statusCode = null, bool allowMultipleExamples = false, JsonSerializerSettings customJsonSerializerSettings = null)
        {
            var type = example.GetType();

            schemaRegistry.GetOrRegister(type);

            var actualTypeName = type.Name.Replace("[]", string.Empty);
            var schema         = schemaRegistry.Definitions[actualTypeName];

            if (!allowMultipleExamples)
            {
                schema.Example = example.UseCustomJsonSerializerSettings(customJsonSerializerSettings);
                return(schema);
            }

            string exampleFakeTypeName;

            if (statusCode == null)
            {
                exampleFakeTypeName = "examples<=" + actualTypeName + "<=" + operationId;
            }
            else
            {
                exampleFakeTypeName = "examples=>" + operationId + "=>" + statusCode + "=>" + actualTypeName;
            }

            //Why? https://github.com/domaindrivendev/Ahoy/issues/228 and https://github.com/domaindrivendev/Swashbuckle/issues/397
            schemaRegistry.Definitions.Add(exampleFakeTypeName, new Schema
            {
                Ref        = "#/definitions/" + exampleFakeTypeName,
                Example    = example.UseCustomJsonSerializerSettings(customJsonSerializerSettings),
                Properties = schema?.Properties
            });

            return(schemaRegistry.Definitions[exampleFakeTypeName]);
        }
コード例 #24
0
ファイル: SwaggerGenerator.cs プロジェクト: GoGoBlitz/Ahoy
        private IParameter CreateParameter(ApiParameterDescription paramDesc, ISchemaRegistry schemaRegistry)
        {
            var source = paramDesc.Source.Id.ToLower();
            var schema = (paramDesc.Type != null) ? schemaRegistry.GetOrRegister(paramDesc.Type) : null;

            if (source == "body")
            {
                return new BodyParameter
                {
                    Name = paramDesc.Name,
                    In = source,
                    Required = paramDesc.IsRequired(),
                    Schema = schema
                };
            }
            else
            {
                var nonBodyParam = new NonBodyParameter
                {
                    Name = paramDesc.Name,
                    In = source,
                    Required = paramDesc.IsRequired()
                };
                if (schema != null) nonBodyParam.PopulateFrom(schema);
                return nonBodyParam;
            }
        }
コード例 #25
0
        private IParameter CreateParameter(ApiParameterDescription paramDesc, ISchemaRegistry schemaRegistry)
        {
            var source = paramDesc.Source.Id.ToLower();
            var schema = (paramDesc.Type == null) ? null : schemaRegistry.GetOrRegister(paramDesc.Type);

            if (source == "body")
            {
                return new BodyParameter
                {
                    Name = paramDesc.Name,
                    In = source,
                    Schema = schema
                };
            }
            else
            {
                var nonBodyParam = new NonBodyParameter
                {
                    Name = paramDesc.Name,
                    In = source,
                    Required = (source == "path")
                };

                if (schema == null)
                    nonBodyParam.Type = "string";
                else
                    nonBodyParam.PopulateFrom(schema);

                if (nonBodyParam.Type == "array")
                    nonBodyParam.CollectionFormat = "multi";

                return nonBodyParam;
            }
        }
コード例 #26
0
 private Response CreateSuccessResponse(Type responseType, ISchemaRegistry schemaRegistry)
 {
     return new Response
     {
         Description = "OK",
         Schema = (responseType != null)
             ? schemaRegistry.GetOrRegister(responseType)
             : null
     };
 }
コード例 #27
0
 /// <inheritdoc/>
 public Schema ProvideFor(Type type, ISchemaRegistry registry, SchemaIdManager idManager)
 {
     return(registry.GetOrRegister(type.GetConceptValueType()));
 }
コード例 #28
0
        private static void SetRequestModelExamples(Operation operation, ISchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var actionAttributes = apiDescription
                                   .ActionAttributes()
                                   .OfType <SwaggerRequestExampleAttribute>();

            foreach (var attr in actionAttributes)
            {
                var schema = schemaRegistry.GetOrRegister(attr.RequestType);

                var bodyParameters = operation.Parameters.Where(p => p.In == "body").Cast <BodyParameter>();
                var request        = bodyParameters.FirstOrDefault(p => p?.Schema.Ref == schema.Ref || p.Schema?.Items?.Ref == schema.Ref);

                if (request == null)
                {
                    continue; // The type in their [SwaggerRequestExample(typeof(requestType), ...] is not passed to their controller action method
                }

                var    provider = ExamplesProvider(_services, attr.ExamplesProviderType);
                string name     = null;
                // var name = attr.RequestType.Name; // this doesn't work for generic types, so need to to schema.ref split
                var parts = schema.Ref?.Split('/');

                if (parts != null)
                {
                    name = parts.Last();
                }
                else
                {
                    // schema.Ref can be null for some types, so we have to try get it by attr.RequestType.Name
                    if (attr.RequestType.GetTypeInfo().IsGenericType)
                    {
                        // remove `# from the generic type name
                        var friendlyName = attr.RequestType.Name.Remove(attr.RequestType.Name.IndexOf('`'));
                        // for generic, Schema will be TypeName[GenericTypeName]
                        name = $"{friendlyName}[{string.Join(",", attr.RequestType.GetGenericArguments().Select(a => a.Name).ToList())}]";
                    }
                    else
                    {
                        name = attr.RequestType.Name;
                    }
                }

                if (string.IsNullOrEmpty(name))
                {
                    continue;
                }

                var serializerSettings = SerializerSettings(attr.ContractResolver, attr.JsonConverter);

                if (schemaRegistry.Definitions.ContainsKey(name))
                {
                    var definitionToUpdate = schemaRegistry.Definitions[name];
                    definitionToUpdate.Example = FormatJson(provider, serializerSettings, false);
                }
                else
                {
                    // schema not found in registry, so put example directly on request schema
                    request.Schema.Example = FormatJson(provider, serializerSettings, false);
                }
            }
        }