Example #1
0
            public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
            {
                schemaRegistry.GetOrRegister(typeof(GeolocateResponse));
                schemaRegistry.GetOrRegister(typeof(CountingLock1));
                schemaRegistry.GetOrRegister(typeof(CountingLock2));
                schemaRegistry.GetOrRegister(typeof(Coordinate));

                if (swaggerDoc.definitions != null && swaggerDoc.definitions.ContainsKey("Company"))
                {
                    swaggerDoc.definitions.Add("Company123", swaggerDoc.definitions["Company"]);
                }
                if (swaggerDoc.paths != null && swaggerDoc.paths.ContainsKey("/api/Company"))
                {
                    var get      = swaggerDoc.paths["/api/Company"].get;
                    var response = get.responses["200"];
                    response.schema.@ref = "#/definitions/Company123";
                    response.description =
                        "## MARKDOWN DoubleHash \n" +
                        "### MARKDOWN TripleHash \n" +
                        "`MARKDOWN code` \n " + get.description;

                    var post = swaggerDoc.paths["/api/Company"].post;
                    post.description = "foo | bar\r\n----|----\r\nbaz | qux | quux";
                }
            }
Example #2
0
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var attributes = apiDescription.ActionDescriptor.GetCustomAttributes <SwaggerResponseAttribute>();

            if (operation.responses == null)
            {
                operation.responses = new Dictionary <string, Response>();
            }
            foreach (var code in _codes)
            {
                var codeNum  = ((int)code).ToString();
                var codeName = code.ToString();
                // добавляем описание
                if (!operation.responses.ContainsKey(codeNum))
                {
                    operation.responses.Add(codeNum,
                                            new Response {
                        description = codeName, schema = schemaRegistry.GetOrRegister(typeof(ResponseModel))
                    });
                }

                if (attributes.All(x => x.StatusCode != (int)HttpStatusCode.OK))
                {
                    operation.responses.Remove("200");
                    operation.responses.Add("200",
                                            new Response {
                        description = HttpStatusCode.OK.ToString(), schema = schemaRegistry.GetOrRegister(typeof(ResponseModel))
                    });
                }
            }
        }
Example #3
0
        public static Schema GetOrRegisterResponseType(this SchemaRegistry registry, IEdmModel edmModel, Type type)
        {
            Contract.Requires(registry != null);
            Contract.Requires(type != null);

            if (IsAGenericODataTypeThatShouldBeUnwrapped(type, MessageDirection.Output))
            {
                return(HandleGenericODataTypeThatShouldBeUnwrapped(registry, edmModel, type));
            }
            Type elementType;

            if (IsResponseCollection(type, MessageDirection.Output, out elementType))
            {
                var openListType  = typeof(List <>);
                var listType      = openListType.MakeGenericType(elementType);
                var openOdataType = typeof(ODataResponse <>);
                var odataType     = openOdataType.MakeGenericType(listType);
                var schema        = registry.GetOrRegister(odataType);
                ApplyEdmModelPropertyNamesToSchema(registry, edmModel, elementType);
                return(schema);
            }
            if (IsResponseWithPrimiveTypeNotSupportedByJson(type, MessageDirection.Output))
            {
                var openOdataType = typeof(ODataResponse <>);
                var odataType     = openOdataType.MakeGenericType(type);
                var schema        = registry.GetOrRegister(odataType);
                return(schema);
            }
            var schema1 = registry.GetOrRegister(type);

            ApplyEdmModelPropertyNamesToSchema(registry, edmModel, type);
            return(schema1);
        }
        public static Schema GetOrRegisterODataType(this SchemaRegistry registry, Type type)
        {
            Contract.Requires(registry != null);
            Contract.Requires(type != null);

            var isAGenericODataType = IsAGenericODataType(type);

            return(isAGenericODataType
                ? registry.GetOrRegister(type.GetGenericArguments()[0])
                : registry.GetOrRegister(type));
        }
        public void GetOrRegister_registerMultiple_DifferentType_SameName_ThrowsError()
        {
            var          mock     = new Mock <JsonSerializerSettings>();
            var          opt      = new SwaggerGeneratorOptions();
            var          schema   = new SchemaRegistry(mock.Object, opt);
            var          model1   = new { Property1 = "Property1" };
            var          model2   = new { Property2 = "Property2" };
            const string testType = "testTypeName";

            schema.GetOrRegister(model1.GetType(), testType);
            Assert.Throws <InvalidOperationException>(() => schema.GetOrRegister(model2.GetType(), testType));
        }
        private Schema GetMessageSchema(SchemaRegistry registry, Type message)
        {
            if (message == null || typeof(Unit).IsAssignableFrom(message))
            {
                return(registry.GetOrRegister(typeof(Message)));
            }
            var schema     = registry.GetOrRegister(typeof(Message <>).MakeGenericType(message));
            var definition = GetReferencedSchema(registry, schema);

            definition.example = CreateExampleMessage(message);
            return(schema);
        }
Example #7
0
            public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
            {
                schemaRegistry.GetOrRegister(typeof(CountingLock1));
                schemaRegistry.GetOrRegister(typeof(CountingLock2));

                if (swaggerDoc.definitions != null && swaggerDoc.definitions.ContainsKey("Company"))
                {
                    swaggerDoc.definitions.Add("Company123", swaggerDoc.definitions["Company"]);
                }
                if (swaggerDoc.paths != null && swaggerDoc.paths.ContainsKey("/api/Company"))
                {
                    swaggerDoc.paths["/api/Company"].get.responses["200"].schema.@ref = "#/definitions/Company123";
                }
            }
        public void GetOrRegister_registerMultiple_SameType_SameName_RegistersOne()
        {
            var          mock     = new Mock <JsonSerializerSettings>();
            var          opt      = new SwaggerGeneratorOptions();
            var          schema   = new SchemaRegistry(mock.Object, opt);
            var          model    = new { Property1 = "Property1" };
            const string testType = "testTypeName";

            schema.GetOrRegister(model.GetType(), testType);
            schema.GetOrRegister(model.GetType(), testType);

            Assert.That(schema.Definitions, Is.Not.Null.And.Count.EqualTo(1));
            Assert.That(schema.Definitions, Contains.Key(testType));
            Assert.That(schema.Definitions[testType].properties, Is.Not.Null.And.ContainKey("Property1"));
        }
        public static Schema GetOrRegisterODataType(this SchemaRegistry registry, Type type)
        {
            Contract.Requires(registry != null);
            Contract.Requires(type != null);

            var isAGenericODataType = IsAGenericODataType(type);

            if (isAGenericODataType)
            {
                var genericArguments = type.GetGenericArguments();
                Contract.Assume(genericArguments != null);
                return(registry.GetOrRegister(genericArguments[0]));
            }
            return(registry.GetOrRegister(type));
        }
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var orderedEnumerable = from attr in apiDescription.GetControllerAndActionAttributes <ODataTypedSwaggerResponse>()
                                    orderby attr.StatusCode
                                    select attr;

            foreach (var current in orderedEnumerable)
            {
                Type type = null;

                var controller = apiDescription.ActionDescriptor.ControllerDescriptor.ControllerType;

                if (typeof(ControllerBase).IsAssignableFrom(controller))
                {
                    type = controller.BaseType.GetGenericArguments()[0];

                    if (current.IsCollection)
                    {
                        type = typeof(IEnumerable <>).MakeGenericType(type);
                    }
                }

                string text = ((int)current.StatusCode).ToString();
                operation.responses[text] = new Response
                {
                    description = (current.Description ?? this.InferDescriptionFrom(text)),
                    schema      = ((type != null) ? schemaRegistry.GetOrRegister(type) : null)
                };

                operation.responses = operation.responses.OrderByDescending(r => r.Key).ToDictionary(p => p.Key, p => p.Value);
            }
        }
Example #11
0
        /// <summary>
        /// Ensures that the 200 response message schmea is present with the correct
        /// type and that the 202 response message schema is cleared out
        /// </summary>
        /// <param name="operation">Metadata for the polling operation of a polling trigger</param>
        /// <param name="pollingResponseType">Type of the polling response</param>
        /// <param name="schemaRegistry">Current registry of schemas used in the metadata</param>
        private static void applyResponseSchemas(Operation operation, Type pollingResponseType, SchemaRegistry schemaRegistry)
        {
            if (operation.responses == null)
            {
                operation.responses = new Dictionary <string, Response>();
            }

            if (!operation.responses.ContainsKey(Constants.HAPPY_POLL_NO_DATA_RESPONSE_CODE))
            {
                operation.responses.Add(Constants.HAPPY_POLL_NO_DATA_RESPONSE_CODE, new Response()
                {
                    description = "Successful poll, but no data available"
                });
            }

            operation.responses[Constants.HAPPY_POLL_NO_DATA_RESPONSE_CODE].schema = null;

            if (!operation.responses.ContainsKey(Constants.HAPPY_POLL_WITH_DATA_RESPONSE_CODE))
            {
                operation.responses.Add(Constants.HAPPY_POLL_WITH_DATA_RESPONSE_CODE, new Response()
                {
                    description = "Successful poll with data available"
                });
            }

            operation.responses[Constants.HAPPY_POLL_WITH_DATA_RESPONSE_CODE].schema
                = pollingResponseType == null ? null : schemaRegistry.GetOrRegister(pollingResponseType);
        }
        private Parameter CreateParameter(string location, ApiParameterDescription paramDesc, SchemaRegistry schemaRegistry)
        {
            var parameter = new Parameter
            {
                @in  = location,
                name = paramDesc.Name
            };

            if (paramDesc.ParameterDescriptor == null)
            {
                parameter.type     = "string";
                parameter.required = true;
                return(parameter);
            }

            parameter.required = location == "path" || !paramDesc.ParameterDescriptor.IsOptional;
            parameter.@default = paramDesc.ParameterDescriptor.DefaultValue;

            var schema = schemaRegistry.GetOrRegister(paramDesc.ParameterDescriptor.ParameterType);

            if (parameter.@in == "body")
            {
                parameter.schema = schema;
            }
            else
            {
                parameter.PopulateFrom(schema);
            }

            return(parameter);
        }
Example #13
0
        private static void SetRequestModelExamples(
            Operation operation,
            SchemaRegistry schemaRegistry,
            ApiDescription apiDescription)
        {
            var requestAttributes =
                apiDescription.GetControllerAndActionAttributes <SwaggerRequestExamplesAttribute>();

            foreach (var attr in requestAttributes)
            {
                var schema = schemaRegistry.GetOrRegister(attr.ResponseType);

                var request = operation.parameters.FirstOrDefault(p => p.@in == "body" && p.schema.@ref == schema.@ref);

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

                    var parts = [email protected]('/');
                    var name  = parts.Last();

                    var definitionToUpdate = schemaRegistry.Definitions[name];

                    if (definitionToUpdate != null)
                    {
                        definitionToUpdate.example = ((dynamic)FormatAsJson(provider))["application/json"];
                    }
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="swaggerDoc"></param>
        /// <param name="schemaRegistry"></param>
        /// <param name="apiExplorer"></param>
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            schemaRegistry.GetOrRegister(typeof(Job));

            var paths = new Dictionary <string, PathItem>(swaggerDoc.paths);

            swaggerDoc.paths.Clear();
            var showDetailAPIOperations = ConfigurationManager.AppSettings["ShowDetailAPIOperations"];

            showDetailAPIOperations = showDetailAPIOperations ?? "0";

            var showAdminAPIOperations = ConfigurationManager.AppSettings["ShowAdminAPIOperations"];

            showAdminAPIOperations = showAdminAPIOperations ?? "0";

            foreach (var path in paths)
            {
                if (path.Key.ToLower().Contains("admin") && showAdminAPIOperations == "1")
                {
                    swaggerDoc.paths.Add(path);
                }
                if (path.Key.ToLower().Contains("detail") && showDetailAPIOperations == "1")
                {
                    swaggerDoc.paths.Add(path);
                }

                if (!path.Key.ToLower().Contains("detail") && !path.Key.ToLower().Contains("admin"))
                {
                    swaggerDoc.paths.Add(path);
                }
            }
        }
Example #15
0
        private static void ApplyEdmModelPropertyNamesToSchema(SchemaRegistry registry, IEdmModel edmModel, Type type)
        {
            var entityReference = registry.GetOrRegister(type);

            if (entityReference.@ref != null)
            {
                var definitionKey    = [email protected]("#/definitions/", string.Empty);
                var schemaDefinition = registry.Definitions[definitionKey];
                var edmType          = edmModel.GetEdmType(type) as IEdmStructuredType;
                if (edmType != null)
                {
                    var edmProperties = new Dictionary <string, Schema>();
                    foreach (var property in schemaDefinition.properties)
                    {
                        var currentProperty = type.GetProperty(property.Key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                        var edmPropertyName = GetEdmPropertyName(currentProperty, edmType);
                        if (edmPropertyName != null)
                        {
                            edmProperties.Add(edmPropertyName, property.Value);
                        }
                    }
                    schemaDefinition.properties = edmProperties;
                }
            }
        }
        private static void SetRequestModelExamples(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var requestAttributes = apiDescription.GetControllerAndActionAttributes <SwaggerRequestExampleAttribute>();

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

                var parameter = operation.parameters.FirstOrDefault(p => p.@in == "body" && p.schema.@ref == schema.@ref);

                if (parameter != null)
                {
                    var provider = (IExamplesProvider)Activator.CreateInstance(attr.ExamplesProviderType);

                    var parts = [email protected]('/');
                    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"];
                    }
                }
            }
        }
        private static Parameter CreateParameter(ApiParameterDescription paramDesc, bool inPath, SchemaRegistry schemaRegistry)
        {
            Contract.Requires(paramDesc != null);
            Contract.Requires(schemaRegistry != null);
            Contract.Assume(paramDesc.ParameterDescriptor != null);

            var @in = inPath
                ? "path"
                : paramDesc.Source == ApiParameterSource.FromUri ? "query" : "body";

            var parameter = new Parameter
            {
                name = paramDesc.Name,
                @in  = @in
            };

            parameter.required = inPath || !paramDesc.ParameterDescriptor.IsOptional;
            parameter.@default = paramDesc.ParameterDescriptor.DefaultValue;

            var schema = schemaRegistry.GetOrRegister(paramDesc.ParameterDescriptor.ParameterType);

            if (parameter.@in == "body")
            {
                parameter.schema = schema;
            }
            else
            {
                parameter.PopulateFrom(schema);
            }

            return(parameter);
        }
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            if (apiDescription.GetControllerAndActionAttributes <SwaggerResponseRemoveDefaultsAttribute>().Any())
            {
                operation.responses.Clear();
            }

            var responseAttributes = apiDescription
                                     .GetControllerAndActionAttributes <SwaggerResponseAttribute>()
                                     .OrderBy(attr => attr.StatusCode);

            foreach (var attr in responseAttributes)
            {
                var statusCode = attr.StatusCode.ToString();

                operation.responses[statusCode] = new Response
                {
                    description = attr.Description ?? InferDescriptionFrom(statusCode),
                    schema      = (attr.Type != null) ? schemaRegistry.GetOrRegister(attr.Type, attr.TypeName) : null
                };
            }

            var mediaTypes = responseAttributes
                             .Where(x => !string.IsNullOrEmpty(x.MediaType))
                             .Select(x => x.MediaType).ToList();

            if (mediaTypes.Count > 0)
            {
                operation.produces = mediaTypes;
            }
        }
        public void Apply(
            Operation operation,
            SchemaRegistry schemaRegistry,
            ApiDescription apiDescription)
        {
            //SetRequestModelExamples(operation, schemaRegistry, apiDescription);
            //SetResponseModelExamples(operation, schemaRegistry, apiDescription);

            var responseAttributes = apiDescription
                                     .GetControllerAndActionAttributes <SwaggerResponseExamplesAttribute>();

            foreach (var attr in responseAttributes)
            {
                var schema = schemaRegistry.GetOrRegister(attr.ResponseType);

                var response = operation.responses.FirstOrDefault
                                   (x => x.Value.schema.type == schema.type &&
                                   x.Value.schema.@ref == schema.@ref).Value;

                if (response != null)
                {
                    var provider = (IProvideExamples)Activator.CreateInstance(attr.ExamplesType);
                    response.examples = FormatAsJson(provider);
                }
            }
        }
        private static void SetRequestModelExamples(Operation operation, SchemaRegistry schemaRegistry,
                                                    ApiDescription apiDescription)
        {
            var requestAttributes = apiDescription.GetControllerAndActionAttributes <SwaggerRequestExample>();

            if (!requestAttributes.Any())
            {
                return;
            }

            operation.consumes.Add("multipart/form-data");
            //  var reportProblemSchema = schemaRegistry.GetOrRegister(typeof (ReportProblem));
            operation.parameters = new[]
            {
                new Parameter
                {
                    name        = "file",
                    @in         = "formData",
                    required    = false,
                    type        = "file",
                    description = "File to attach"
                },
                new Parameter
                {
                    name     = "payload",
                    @in      = "formData",
                    required = true,
                    type     = "object",
                    //     schema = reportProblemSchema,
                    description = "Other related data"
                }
            };

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

                var parameter = operation.parameters.FirstOrDefault(p => p.type == "object");
                if (parameter == null)
                {
                    continue;
                }

                parameter.schema = schema;

                var provider = (IExamplesProvider)Activator.CreateInstance(attr.ExamplesProviderType);

                var parts = [email protected]('/');
                var name  = parts.Last();

                var definitionToUpdate = schemaRegistry.Definitions[name];

                if (definitionToUpdate != null)
                {
                    definitionToUpdate.example = ((dynamic)FormatAsJson(provider))["application/json"];
                    parameter.@default         = ((dynamic)FormatAsJson(provider))["application/json"].ToString();
                }
            }
        }
 public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
 {
     if (operation.operationId == "Controller_ActionName")  // controller and action name
     {
        var refSchema = schemaRegistry.GetOrRegister(typeof(List<ImageFeature>));
 
         //here you can create a new Parameter of type Array and then call the
         //param.PopulateFrom(schema);
     }
 }            
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var errorSchema = schemaRegistry.GetOrRegister(typeof(HttpError));

            operation.responses.Add("default", new Response
            {
                description = "Error",
                schema      = errorSchema
            });
        }
Example #23
0
        private static Schema HandleGenericODataTypeThatShouldBeUnwrapped(SchemaRegistry registry, IEdmModel edmModel, Type type)
        {
            var genericArguments = type.GetGenericArguments();

            Contract.Assume(genericArguments != null);
            var schema = registry.GetOrRegister(genericArguments[0]);

            ApplyEdmModelPropertyNamesToSchema(registry, edmModel, genericArguments[0]);
            return(schema);
        }
Example #24
0
            public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
            {
                schemaRegistry.GetOrRegister(typeof(ExtraType));
                //schemaRegistry.GetOrRegister(typeof(BigClass));
                foreach (var type in ContractTypes(typeof(ContractClassAttribute)))
                {
                    schemaRegistry.GetOrRegister(type);
                }

                var paths = new Dictionary <string, PathItem>(swaggerDoc.paths);

                swaggerDoc.paths.Clear();
                foreach (var path in paths)
                {
                    if (path.Key.Contains("foo"))
                    {
                        swaggerDoc.paths.Add(path);
                    }
                }
            }
        private static void ApplyEdmModelPropertyNamesToSchema(SchemaRegistry registry, IEdmModel edmModel, Type type)
        {
            var entityReference        = registry.GetOrRegister(type);
            var hasDataMemberAttribute = false;

            if (entityReference.@ref != null)
            {
                var definitionKey    = [email protected]("#/definitions/", string.Empty);
                var schemaDefinition = registry.Definitions[definitionKey];
                var edmType          = edmModel.GetEdmType(type) as IEdmStructuredType;
                if (edmType != null)
                {
                    var edmProperties = new Dictionary <string, Schema>();
                    foreach (var property in schemaDefinition.properties)
                    {
                        string key = string.Empty;
                        if (type.IsDefined(typeof(DataContractAttribute), true))
                        {
                            var originalProperty = type.GetProperties()
                                                   .Where(p => p.GetCustomAttributes(typeof(DataMemberAttribute), true)
                                                          .OfType <DataMemberAttribute>()
                                                          .Any(x => x.Name == property.Key))
                                                   .FirstOrDefault();
                            // this can happen if the DataMemberAttributes Name is the same as the Property...
                            if (originalProperty != null)
                            {
                                hasDataMemberAttribute = true;
                                key = originalProperty.Name;
                            }
                            else
                            {
                                key = property.Key;
                            }
                        }
                        else
                        {
                            key = property.Key;
                        }
                        var currentProperty = type.GetProperty(key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);


                        var edmPropertyName = GetEdmPropertyName(currentProperty, edmType, hasDataMemberAttribute ? property.Key : currentProperty.Name);

                        if (edmPropertyName != null)
                        {
                            edmProperties.Add(edmPropertyName, property.Value);
                        }
                    }
                    schemaDefinition.properties = edmProperties;
                }
            }
        }
        public static void SetTrigger(this Operation operation, SchemaRegistry schemaRegistry, TriggerAttribute triggerDescription)
        {
            operation.EnsureVendorExtensions();

            string batchMode = null;

            switch (triggerDescription.Pattern)
            {
            case TriggerType.PollingBatched:
                batchMode = Constants.BATCH;
                break;

            case TriggerType.PollingSingle:
                batchMode = Constants.SINGLE;
                break;

            case TriggerType.Subscription:
                batchMode = Constants.SINGLE;
                operation.SetCallbackType(schemaRegistry, triggerDescription.DataType, triggerDescription.DataFriendlyName);
                break;

            default:
                break;
            }

            if (!operation.vendorExtensions.ContainsKey(Constants.X_MS_TRIGGER))
            {
                operation.vendorExtensions.Add(Constants.X_MS_TRIGGER,
                                               batchMode.ToString().ToLowerInvariant());
            }

            if (triggerDescription.Pattern == TriggerType.Subscription)
            {
                return;
            }

            var dataResponse = new Response()
            {
                description = triggerDescription.DataFriendlyName,
                schema      = null != triggerDescription.DataType
                            ? schemaRegistry.GetOrRegister(triggerDescription.DataType)
                            : null
            };

            var acceptedResponse = new Response()
            {
                description = Constants.ACCEPTED
            };

            operation.responses[Constants.HAPPY_POLL_WITH_DATA_RESPONSE_CODE] = dataResponse;
            operation.responses[Constants.HAPPY_POLL_NO_DATA_RESPONSE_CODE]   = acceptedResponse;
        }
        public void GetOrRegister_withTypeName()
        {
            var          mock     = new Mock <JsonSerializerSettings>();
            var          opt      = new SwaggerGeneratorOptions();
            var          schema   = new SchemaRegistry(mock.Object, opt);
            var          model    = new { Property1 = "Property1" };
            const string typeName = "testTypeName";

            schema.GetOrRegister(model.GetType(), typeName);

            Assert.That(schema.Definitions, Is.Not.Null.And.ContainKey(typeName));
            Assert.That(schema.Definitions[typeName].properties, Is.Not.Null.And.ContainKey("Property1"));
        }
Example #28
0
        public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
        {
            if (type.BaseType != null && !type.BaseType.Equals(typeof(object)))
            {
                if (schema.allOf == null)
                {
                    schema.allOf = new List <Schema>();
                }

                var parentSchema = schemaRegistry.GetOrRegister(type.BaseType);
                schema.allOf.Add(parentSchema);
            }
        }
Example #29
0
        private Operation CreateOperation(ApiDescription apiDesc, SchemaRegistry schemaRegistry, float apiVersion)
        {
            var parameters = apiDesc.ParameterDescriptions
                .Select(paramDesc =>
                {
                    string location = GetParameterLocation(apiDesc, paramDesc);
                    return CreateParameter(location, paramDesc, schemaRegistry);
                })
                 .ToList();

            var responses = new Dictionary<string, Response>();
            var responseType = apiDesc.ResponseType();
            if (responseType == null || responseType == typeof(void))
                responses.Add("204", new Response { description = "No Content" });
            else
                responses.Add("200", new Response { description = "OK", schema = schemaRegistry.GetOrRegister(responseType) });

            var operation = new Operation
            {
                tags = new[] { _options.GroupingKeySelector(apiDesc) },
                operationId = apiDesc.FriendlyId(),
                produces = apiDesc.Produces().ToList(),
                consumes = apiDesc.Consumes().ToList(),
                parameters = parameters.Any() ? parameters : new List<Parameter>(), // parameters can be null but not empty
                responses = responses,
                deprecated = apiDesc.IsObsolete() ? true : (bool?)null
            };
            
            if (apiVersion>2)
            {
                operation.parameters.Insert(0, new Parameter { name = "JWT", @in = "header", description = "Json Web Token", required = false, type = "string" });
            }
            else
            {
                //appInfo控制器排除
                if (apiDesc.ActionDescriptor.ControllerDescriptor.ControllerName!=nameof(Controllers.v1.AppInfoController))
                {
                    operation.parameters.Insert(0, new Parameter { name = "AppKey", @in = "header", description = "客户端标识", required = false, type = "string" });
                    operation.parameters.Insert(1, new Parameter { name = "Sign", @in = "header", description = "签名", required = false, type = "string" });
                }
            }
            

            foreach (var filter in _options.OperationFilters)
            {
                filter.Apply(operation, schemaRegistry, apiDesc);
            }

            return operation;
        }
        public void GetOrRegister_withoutTypeName()
        {
            string SchemaIdSelector(Type arg) => arg.FullName;

            var mock = new Mock <JsonSerializerSettings>();
            var opt = new SwaggerGeneratorOptions(schemaIdSelector: SchemaIdSelector);
            var schema = new SchemaRegistry(mock.Object, opt);
            var modelType = new { Property1 = "Property1" }.GetType();

            schema.GetOrRegister(modelType);

            Assert.That(schema.Definitions, Is.Not.Null.And.ContainKey(SchemaIdSelector(modelType)));
            Assert.That(schema.Definitions[SchemaIdSelector(modelType)].properties, Is.Not.Null.And.ContainKey("Property1"));
        }
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            if (apiDescription.GetControllerAndActionAttributes<SwaggerResponseRemoveDefaultsAttribute>().Any()) 
                operation.responses.Clear();

            var responseAttributes = apiDescription.GetControllerAndActionAttributes<SwaggerResponseAttribute>()
                .OrderBy(attr => attr.StatusCode);

            foreach (var attr in responseAttributes)
            {
                var statusCode = attr.StatusCode.ToString();

                operation.responses[statusCode] = new Response
                {
                    description = attr.Description ?? InferDescriptionFrom(statusCode),
                    schema = (attr.Type != null) ? schemaRegistry.GetOrRegister(attr.Type) : null
                };
            }
        }
        private void HandleFromUriObjectParams(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var fromUriObjectParams = operation.parameters
                .Where(param => param.@in == "query" && param.type == null)
                .ToArray();

            foreach (var objectParam in fromUriObjectParams)
            {
                var type = apiDescription.ParameterDescriptions
                    .Single(paramDesc => paramDesc.Name == objectParam.name)
                    .ParameterDescriptor.ParameterType;

                var refSchema = schemaRegistry.GetOrRegister(type);
                var schema = schemaRegistry.Definitions[[email protected]("#/definitions/", "")];

                var qualifier = string.IsNullOrEmpty(objectParam.name) ? "" : (objectParam.name + ".");
                ExtractAndAddQueryParams(schema, qualifier, objectParam.required, schemaRegistry, operation.parameters);
                operation.parameters.Remove(objectParam);
            }
        }