public void Apply(Operation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null)
            {
                return;
            }

            var formFileParams = context.ApiDescription.ActionDescriptor.Parameters
                                 .Where(x => x.ParameterType.IsAssignableFrom(typeof(IFormFile)))
                                 .Select(x => x.Name)
                                 .ToList();;

            var formFileSubParams = context.ApiDescription.ActionDescriptor.Parameters
                                    .SelectMany(x => x.ParameterType.GetProperties())
                                    .Where(x => x.PropertyType.IsAssignableFrom(typeof(IFormFile)))
                                    .Select(x => x.Name)
                                    .ToList();

            var allFileParamNames = formFileParams.Union(formFileSubParams);

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

            var paramsToRemove = new List <IParameter>();

            foreach (var param in operation.Parameters)
            {
                paramsToRemove.AddRange(from fileParamName in allFileParamNames where param.Name.StartsWith(fileParamName + ".") select param);
            }
            paramsToRemove.ForEach(x => operation.Parameters.Remove(x));
            foreach (var paramName in allFileParamNames)
            {
                var fileParam = new NonBodyParameter
                {
                    Type = "file",
                    Name = paramName,
                    In   = "formData"
                };
                operation.Parameters.Add(fileParam);
            }
            foreach (IParameter param in operation.Parameters)
            {
                param.In = "formData";
            }

            operation.Consumes = new List <string>()
            {
                "multipart/form-data"
            };
        }
Exemple #2
0
        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);
        }
        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);
        }
        public void Apply(Operation operation, OperationFilterContext context)
        {
            var apiVersion = context.ApiDescription.GetApiVersion();

            // If the api explorer did not capture an API version for this operation then the action must be API
            // version-neutral, so there's nothing to add.
            if (apiVersion == null)
            {
                return;
            }

            var parameters = operation.Parameters;

            if (parameters == null)
            {
                operation.Parameters = parameters = new List <IParameter>();
            }

            // Note: In most applications, service authors will choose a single, consistent approach to how API
            // versioning is applied. this sample uses:
            // 1. Query string parameter method with the name "api-version".
            // 2. URL path segment with the route parameter name "api-version".
            // Unless you allow multiple API versioning methods in your app, your implementation could be simpler.

            // consider the url path segment parameter first
            var parameter = parameters.FirstOrDefault(p => p.Name == "api-version");

            switch (parameter)
            {
            case null:
                // the only other method in this sample is by query string
                parameter = new NonBodyParameter()
                {
                    Name     = "api-version",
                    Required = true,
                    Default  = apiVersion.ToString(),
                    In       = "query",
                    Type     = "string",
                };
                parameters.Add(parameter);
                break;

            case NonBodyParameter pathParameter:
                // Update the default value with the current API version so that the route can be invoked in the
                // "Try It!" feature.
                pathParameter.Default = apiVersion.ToString();
                break;
            }

            parameter.Description = "The requested API version";
        }
        private IParameter CreateServiceKeyParameter()
        {
            var nonBodyParam = new NonBodyParameter
            {
                Name     = "servicekey",
                In       = "query",
                Required = false,
            };
            var schema = new Schema();

            schema.Description = "ServiceKey";
            nonBodyParam.PopulateFrom(schema);
            return(nonBodyParam);
        }
Exemple #6
0
        IParameter CreateFormParameterWithNameAndType(string name, string location, Type type)
        {
            var parameter = new NonBodyParameter
            {
                Name     = name,
                In       = location,
                Required = true,
            };
            var schema = _schemaRegistryFactory.Create().GetOrRegister(type);

            parameter.Type   = schema.Type;
            parameter.Format = schema.Format;
            return(parameter);
        }
Exemple #7
0
        private IParameter CreateNonBodyParameter(
            string name,
            string location,
            Schema schema,
            ISchemaRegistry schemaRegistry,
            bool isRequired,
            IEnumerable <object> customAttributes,
            ParameterInfo parameterInfo)
        {
            var nonBodyParam = new NonBodyParameter
            {
                Name     = name,
                In       = location,
                Required = (location == "path") ? true : isRequired,
            };

            if (schema == null)
            {
                nonBodyParam.Type = "string";
            }
            else
            {
                if (schema.Ref != null)
                {
                    // It's a referenced Schema and therefore needs to be located. This also 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 and needs to be refactored - SchemaRegistry should be stateless
                    schema.AssignAttributeMetadata(customAttributes);
                    schema.Default = (parameterInfo != null && parameterInfo.IsOptional)
                        ? parameterInfo.DefaultValue
                        : null;
                }

                nonBodyParam.PopulateFrom(schema);
            }

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

            return(nonBodyParam);
        }
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null)
            {
                return;
            }

            var paramFormFile = context.ApiDescription.ActionDescriptor.Parameters
                                .SingleOrDefault(x => x.ParameterType.IsAssignableFrom(typeof(IFormFile)));

            if (paramFormFile == null)
            {
                return;
            }

            var propsParamFormFile = paramFormFile.ParameterType.GetProperties().Select(x => x.Name);

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

            var paramsToRemoveOperation = new List <IParameter>();

            foreach (var param in operation.Parameters)
            {
                if (propsParamFormFile.Contains(param.Name))
                {
                    paramsToRemoveOperation.Add(param);
                }
            }

            paramsToRemoveOperation.ForEach(x => operation.Parameters.Remove(x));

            var fileParam = new NonBodyParameter
            {
                Type = "file",
                Name = paramFormFile.Name,
                In   = "formData"
            };

            operation.Parameters.Add(fileParam);

            foreach (IParameter param in operation.Parameters)
            {
                param.In = "formData";
            }
        }
Exemple #9
0
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null)
            {
                return;
            }

            var formFileParams = context.ApiDescription.ActionDescriptor.Parameters
                                 .Where(x => x.ParameterType.IsAssignableFrom(typeof(IFormFile)))
                                 .Select(x => x.Name)
                                 .ToList();

            var formFileSubParams = context.ApiDescription.ActionDescriptor.Parameters
                                    .SelectMany(x => x.ParameterType.GetProperties())
                                    .Where(x => x.PropertyType.IsAssignableFrom(typeof(IFormFile)))
                                    .Select(x => x.Name)
                                    .ToList();

            var fileParams = formFileParams.Union(formFileSubParams);

            operation.Parameters.Where(param => fileParams.Contains(param.Name))
            .ToList().ForEach(param =>
            {
                operation.Parameters.Remove(param);
            });

            foreach (var paramName in fileParams)
            {
                var fileParam = new NonBodyParameter
                {
                    Type        = "file",
                    Name        = paramName,
                    Description = "Arquivo à ser processado",
                    Required    = true
                };
                operation.Parameters.Add(fileParam);
            }

            foreach (IParameter param in operation.Parameters)
            {
                param.In = "formData";
            }

            operation.Consumes = new List <string>()
            {
                "multipart/form-data"
            };
        }
Exemple #10
0
        public void Apply(Operation operation, OperationFilterContext context)
        {
            var apiDescription = context.ApiDescription;

            operation.Deprecated = apiDescription.IsDeprecated();

            if (operation.Parameters == null)
            {
                return;
            }

            // https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/412
            // https://github.com/domaindrivendev/Swashbuckle.AspNetCore/pull/413
            foreach (var parameter in operation.Parameters.OfType <NonBodyParameter>())
            {
                var description = apiDescription.ParameterDescriptions.First(p => p.Name == parameter.Name);

                if (parameter.Description == null)
                {
                    parameter.Description = description.ModelMetadata?.Description;
                }

                if (parameter.Default == null)
                {
                    parameter.Default = description.DefaultValue;
                }

                parameter.Required |= description.IsRequired;
            }

            var headerParameter = operation.Parameters.FirstOrDefault(a => a.Name.ToLowerInvariant() == "x-api-version");

            if (headerParameter == null)
            {
                headerParameter = new NonBodyParameter
                {
                    Name     = "api-version",
                    In       = "header",
                    Type     = "string",
                    Required = false
                };

                operation.Parameters.Add(headerParameter);
            }

            headerParameter.Required = false;
        }
Exemple #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") || paramDescription.IsRequired()
            };

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

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

            return(nonBodyParam);
        }
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null)
            {
                return;
            }

            // Vyhledani IFormFile názvů parametrů
            var fileParamNames = context.ApiDescription.ActionDescriptor.Parameters
                                 .SelectMany(x => x.ParameterType.GetProperties())
                                 .Where(x => x.PropertyType.IsAssignableFrom(typeof(IFormFile)))
                                 .Select(x => x.Name)
                                 .ToList();

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

            var paramsToRemove = new List <IParameter>();

            paramsToRemove.AddRange(operation.Parameters.Where(p => fileParamNames.Contains(p.Name)));
            paramsToRemove.ForEach(x => operation.Parameters.Remove(x));

            // založení nových parametrů
            foreach (var paramName in fileParamNames)
            {
                var fileParam = new NonBodyParameter
                {
                    Type = "file",
                    Name = paramName,
                    In   = "formData"
                };
                operation.Parameters.Add(fileParam);
            }
            foreach (IParameter param in operation.Parameters)
            {
                param.In = "formData";
            }

            operation.Consumes = new List <string>()
            {
                "multipart/form-data"
            };
        }
        public void Apply(Swashbuckle.Swagger.Model.Operation operation, OperationFilterContext context)
        {
            var apiVersionParam = new NonBodyParameter
            {
                In          = "header",
                Name        = "api-version",
                Type        = "string",
                Description = "Version header parameter",
                Required    = false,
                Default     = "1.0"
            };

            if (operation.Parameters == null)
            {
                operation.Parameters = new List <IParameter>();
            }
            operation.Parameters.Add(apiVersionParam);
        }
Exemple #14
0
 Operation GenerateOperation(Type artifactType, IList <string> tags)
 {
     return(new Operation
     {
         Tags = tags,
         Parameters = _documentGlobalParameters.Concat(artifactType.GetProperties().Where(_documentPropertyFilter).Select(_ => {
             var parameter = new NonBodyParameter
             {
                 Name = _.Name,
                 In = _parameterLocation,
                 Required = true,
             };
             AddSchemaFor(parameter, _schemaRegistry.GetOrRegister(_.PropertyType));
             return (IParameter)parameter;
         })).ToList(),
         Responses = _responses,
     });
 }
        private static void BuildPageableParameters(AutumnSettings settings, Operation operation, Type entityType)
        {
            var genericPageType = typeof(Page <>);
            var pageType        = genericPageType.MakeGenericType(entityType);
            var schema          = GetOrRegistrySchema(pageType, HttpMethod.Get, settings.NamingStrategy);

            operation.Responses = new Dictionary <string, Response>
            {
                { "200", new Response()
                  {
                      Schema = schema, Description = "OK"
                  } },
                { "206", new Response()
                  {
                      Schema = schema, Description = "Partial Content"
                  } }
            };

            IParameter parameter;

            parameter = new NonBodyParameter
            {
                In          = "query",
                Type        = "integer",
                Minimum     = 0,
                Format      = "int32",
                Description = "Size of the page",
                Default     = settings.PageSize,
                Name        = settings.PageSizeField
            };
            operation.Parameters.Add(parameter);

            parameter = new NonBodyParameter
            {
                In          = "query",
                Type        = "integer",
                Description = "Paging number (start to zero)",
                Minimum     = 0,
                Format      = "int32",
                Default     = 0,
                Name        = settings.PageNumberField
            };
            operation.Parameters.Add(parameter);
        }
        /// <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);
        }
Exemple #17
0
        public void Apply(Operation operation, OperationFilterContext context)
        {
            var controllerPolicies = context.ApiDescription.ControllerAttributes()
                                     .OfType <AuthorizeAttribute>()
                                     .Select(attr => attr.AuthenticationSchemes);
            var actionPolicies = context.ApiDescription.ActionAttributes()
                                 .OfType <AuthorizeAttribute>()
                                 .Select(attr => attr.AuthenticationSchemes);
            var policies = controllerPolicies.Union(actionPolicies).Distinct();

            if (policies.Any())
            {
                operation.Responses.Add("401", new Response {
                    Description = "Unauthorized - correct token needed"
                });
                var headerParameter = new NonBodyParameter
                {
                    Name        = "Authorization",
                    In          = "header",
                    Description = "access token",
                    Required    = true,
                    Type        = "string"
                };

                if (operation.Parameters is null)
                {
                    operation.Parameters = new[] { headerParameter };
                }
                else
                {
                    operation.Parameters.Add(headerParameter);
                }


                //operation.Security = new List<IDictionary<string, IEnumerable<string>>>();
                //operation.Security.Add(
                //    new Dictionary<string, IEnumerable<string>>
                //    {
                //        { "Bearer", policies },
                //        //{ "Query string access token", policies }
                //    });
            }
        }
Exemple #18
0
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (context.ApiDescription.ParameterDescriptions.Any(p => p.ModelMetadata.ContainerType == typeof(IFormFile) || p.ModelMetadata.UnderlyingOrModelType == typeof(IFormFile)))
            {
                NonBodyParameter[] formFileParameters = operation
                                                        .Parameters
                                                        .OfType <NonBodyParameter>()
                                                        .Where(p => FormFilePropertyNames.Contains(p.Name) || p.Name == "file")
                                                        .ToArray();

                int index = operation.Parameters.IndexOf(formFileParameters.First());

                foreach (NonBodyParameter formFileParameter in formFileParameters)
                {
                    operation.Parameters.Remove(formFileParameter);
                }

                string formFileParameterName = context
                                               .ApiDescription
                                               .ActionDescriptor
                                               .Parameters
                                               .Where(p => p.ParameterType == typeof(IFormFile))
                                               .Select(p => p.Name)
                                               .First();

                NonBodyParameter parameter = new NonBodyParameter()
                {
                    Name        = formFileParameterName,
                    In          = "formData",
                    Description = "The file to upload.",
                    Required    = true,
                    Type        = "file"
                };

                operation.Parameters.Insert(index, parameter);

                if (!operation.Consumes.Contains(FormDataMimeType))
                {
                    operation.Consumes.Add(FormDataMimeType);
                }
            }
        }
Exemple #19
0
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (context.ApiDescription.ParameterDescriptions.Any(x => x.ModelMetadata.ContainerType == typeof(IFormFile)))
            {
                NonBodyParameter[] formFileParameters = operation
                                                        .Parameters
                                                        .OfType <NonBodyParameter>()
                                                        .Where(x => _formFilePropertyNames.Contains(x.Name))
                                                        .ToArray();

                int parameterIndex = operation.Parameters.IndexOf(formFileParameters.First());

                foreach (NonBodyParameter formFileParameter in formFileParameters)
                {
                    operation.Parameters.Remove(formFileParameter);
                }

                string formFileParameterName = context
                                               .ApiDescription
                                               .ActionDescriptor
                                               .Parameters
                                               .Where(x => x.ParameterType == typeof(IFormFile))
                                               .Select(x => x.Name)
                                               .First();

                NonBodyParameter parameter = new NonBodyParameter()
                {
                    Name        = formFileParameterName,
                    In          = "formData",
                    Description = "The file to upload with \"multipart/form-data\" enctype form.",
                    Required    = true,
                    Type        = "file"
                };

                operation.Parameters.Insert(parameterIndex, parameter);

                if (!operation.Consumes.Contains(_formDataMimeType))
                {
                    operation.Consumes.Add(_formDataMimeType);
                }
            }
        }
            private ParameterContract BuildParameter(NonBodyParameter p)
            {
                if (p != null)
                {
                    string defaultValue = (p.Default != null) ? p.Default.ToString() : null;
                    string description  = (p.Format != null) ? "format - " + p.Format + ". " : "";
                    description += p.Description;

                    if (p.Type == "array")
                    {
                        if (p.Items != null && p.Items.Type != null)
                        {
                            description = "array " + p.Items.Type + ". " + description;
                        }
                    }

                    return(ParameterContract.Create(p.Name, p.Type, description, defaultValue, p.Required));
                }
                return(null);
            }
        public void Apply(Operation operation, OperationFilterContext context)
        {
            var apiVersion = context.ApiDescription.GetApiVersion();

            if (apiVersion == null)
            {
                return;
            }

            var parameters = operation.Parameters;

            if (parameters == null)
            {
                operation.Parameters = parameters = new List <IParameter>();
            }

            var parameter = parameters.SingleOrDefault(p => p.Name == "api-version");

            if (parameter == null)
            {
                parameter = new NonBodyParameter
                {
                    Name     = "api-version",
                    Required = true,
                    Default  = apiVersion.ToString(),
                    In       = "query",
                    Type     = "string"
                };

                parameters.Add(parameter);
            }

            var pathParameter = parameter as NonBodyParameter;

            if (pathParameter != null)
            {
                pathParameter.Default = apiVersion.ToString();
            }

            parameter.Description = "The requested API version";
        }
Exemple #22
0
        public override object ReadJson(
            JsonReader reader,
            Type objectType,
            object existingValue,
            JsonSerializer serializer)
        {
            JObject    jsonObject = JObject.Load(reader);
            IParameter parameter  = null;

            if (jsonObject["in"].ToString() == "body")
            {
                parameter = new BodyParameter();
            }
            else
            {
                parameter = new NonBodyParameter();
            }

            serializer.Populate(jsonObject.CreateReader(), parameter);
            return(parameter);
        }
Exemple #23
0
        public void Apply(Operation operation, OperationFilterContext context)
        {
            var attributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
                             .Union(context.MethodInfo.GetCustomAttributes(true))
                             .OfType <AuthorizeAttribute>();
            var allowAnonymous = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
                                 .Union(context.MethodInfo.GetCustomAttributes(true))
                                 .OfType <AllowAnonymousAttribute>();

            if (attributes.Any() && !allowAnonymous.Any())
            {
                var parameter = new NonBodyParameter
                {
                    Name        = "Authorization",
                    In          = "header",
                    Description = "Access Token",
                    Required    = true
                };
                operation.Parameters.Add(parameter);
            }
        }
Exemple #24
0
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (Options.GlobalParameters?.Any() != true)
            {
                return;
            }

            foreach (var globalParameter in Options.GlobalParameters)
            {
                var parameterInfo = new NonBodyParameter
                {
                    Name        = globalParameter.Name,
                    Required    = globalParameter.IsRequire,
                    In          = globalParameter.In.AsString(EnumFormat.DisplayName),
                    Type        = globalParameter.Type,
                    Description = globalParameter.Description
                };

                operation.Parameters = operation.Parameters.RemoveWhere(x => x.Name == parameterInfo.Name).ToList();

                operation.Parameters.Add(parameterInfo);
            }
        }
Exemple #25
0
        void IOperationFilter.Apply(Operation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null)
            {
                operation.Parameters = new List<IParameter>();
            }

            if (!context.ApiDescription.TryGetMethodInfo(out MethodInfo methodInfo))
            {
                return;
            }

            var authorizeAttributes = methodInfo.DeclaringType
                .GetCustomAttributes(true)
                .Union(context.MethodInfo.GetCustomAttributes(true))
                .OfType<AuthorizeAttribute>();

            var allowAnonymousAttributes = methodInfo.DeclaringType
            .GetCustomAttributes(true)
            .OfType<AllowAnonymousAttribute>();

            if (!authorizeAttributes.Any() && !allowAnonymousAttributes.Any())
            {
                return;
            }

            var parameter = new NonBodyParameter
            {
                Name = "Authorization",
                In = "header",
                Description = "The Bearer token",
                Required = true,
                Type = "string"
            };

            operation.Parameters.Add(parameter);
        }
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null)
            {
                operation.Parameters = new List <IParameter>();
            }

            var authorizeAttributes = context.ApiDescription
                                      .ControllerAttributes()
                                      .Union(context.ApiDescription.ActionAttributes())
                                      .OfType <AuthorizeAttribute>();
            var allowAnonymousAttributes = context.ApiDescription.ActionAttributes().OfType <AllowAnonymousAttribute>();

            if (!authorizeAttributes.Any() && !allowAnonymousAttributes.Any())
            {
                return;
            }
            var parameter = new NonBodyParameter
            {
                Name        = "Content-Type",
                In          = "header",
                Description = "application/json",
                Required    = true,
                Type        = "string"
            };
            var parameter1 = new NonBodyParameter
            {
                Name        = "Authorization",
                In          = "header",
                Description = "The bearer token",
                Required    = true,
                Type        = "string"
            };

            operation.Parameters.Add(parameter);
            operation.Parameters.Add(parameter1);
        }
        private IParameter CreateNonBodyParameter(
            string name,
            string location,
            Schema schema,
            bool isRequired,
            ISchemaRegistry schemaRegistry)
        {
            var nonBodyParam = new NonBodyParameter
            {
                Name     = name,
                In       = location,
                Required = (location == "path") ? true : 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);
        }
Exemple #28
0
        public void Apply(Operation operation, OperationFilterContext context)
        {
            var multipartBodyFilters = context.ApiDescription.ActionDescriptor.FilterDescriptors
                                       .Select(x => x.Filter)
                                       .OfType <MultipartBodyLengthLimitAttribute>()
                                       .ToList();

            if (multipartBodyFilters.Count == 0)
            {
                return;
            }

            var fileParam = new NonBodyParameter
            {
                Type = "file",
                Name = "file",
                In   = "formData"
            };

            operation.Parameters.Add(fileParam);
            operation.Consumes = new List <string> {
                "multipart/form-data"
            };
        }
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (!(context.ApiDescription.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor))
            {
                return;
            }

            var listParameters = controllerActionDescriptor.MethodInfo.GetCustomAttributes <ApiParameterAttribute>(true)
                                 .ToList();

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

            foreach (var parameter in listParameters)
            {
                var parameterInfo = new NonBodyParameter
                {
                    Name        = parameter.Name,
                    Required    = parameter.IsRequire,
                    In          = parameter.In,
                    Type        = parameter.Type,
                    Description = parameter.Description
                };

                if (operation.Parameters?.Any() != true)
                {
                    operation.Parameters = new List <IParameter>();
                }

                operation.Parameters = operation.Parameters.RemoveWhere(x => x.Name == parameterInfo.Name).ToList();

                operation.Parameters.Add(parameterInfo);
            }
        }
        private static List <IParameter> GetParameters(List <JimuServiceParameterDesc> paras, string httpMethod)
        {
            List <IParameter> parameters = new List <IParameter>();
            int           idx            = 0;
            StringBuilder sbExample      = new StringBuilder();

            foreach (var p in paras)
            {
                idx++;
                if (httpMethod == "GET")
                {
                    var param = new NonBodyParameter
                    {
                        Name = p.Name,
                        Type = p.Type,
                        //Format = p.Format,
                        In          = "query",
                        Description = $"{p.Comment}",
                    };
                    //if (typeInfo.IsArray)
                    if (TypeHelper.CheckIsArray(p.Type))
                    {
                        param.Format = null;
                        param.Items  = new PartialSchema
                        {
                            //Type = typeInfo.Type
                            Type = TypeHelper.GetArrayType(p.Type)
                        };
                        param.Type = "array";
                    }
                    if (TypeHelper.CheckIsObject(p.Type))
                    {
                        param.Default = p.Format;
                    }
                    parameters.Add(param);
                }
                else
                {
                    var bodyPara = new BodyParameter
                    {
                        Name        = p.Name,
                        In          = "body",
                        Description = $"{p.Comment}",
                        Schema      = new Schema
                        {
                            Format = p.Format,
                        }
                    };
                    // swagger bug: two or more object parameter in post, when execute it, just post the last one,so we put all parameter in the last one that it can post it
                    if (!string.IsNullOrEmpty(p.Format) && p.Format.IndexOf("{") < 0)
                    {
                        sbExample.Append($"{p.Name}:\"{ p.Format}\",");
                    }
                    else if (!string.IsNullOrEmpty(p.Format))
                    {
                        sbExample.Append($"{p.Name}:{ p.Format},");
                    }
                    if (idx == paras.Count && sbExample.Length > 0 && paras.Count > 1)
                    {
                        bodyPara.Schema.Example = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>($"{{{sbExample.ToString().TrimEnd(',')}}}");
                    }
                    else if (idx == paras.Count && sbExample.Length > 0)
                    {
                        bodyPara.Schema.Example = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>($"{{{sbExample.ToString().TrimEnd(',')}}}");
                    }

                    parameters.Add(bodyPara);
                }
            }
            return(parameters);
        }