public void Apply(Operation operation, OperationFilterContext context)
        {
            var filterPipeline = context.ApiDescription.ActionDescriptor.FilterDescriptors;
            var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Filter).Any(filter => filter is AuthorizeFilter);
            var allowAnonymous = filterPipeline.Select(filterInfo => filterInfo.Filter).Any(filter => filter is IAllowAnonymousFilter);

            if (isAuthorized && !allowAnonymous)
            {
                if (operation.Parameters == null)
                {
                    operation.Parameters = new List<IParameter>();
                }

                var tokenParameter = new NonBodyParameter
                {
                    Type = "string",
                    In = "header",
                    Name = "Authorization",
                    Description = "token",
                    Default = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJsb2NhbGhvc3QiLCJhdXRob3JpdHkiOiJhdXRob3JpdHkiLCJmb28iOiJiYXIiLCJpc3MiOiJ3ZSB0aGUgbWFueSJ9.bm77vM2yQXc93vnc44Rqv_Rkm5OszFa9daM37db6EBg",
                    Required = true
                };

                operation.Parameters.Add(tokenParameter);
            }
        }
 public void Apply(Operation operation, OperationFilterContext context)
 {
     ApplyOperationAttributes(operation, context);
     ApplyOperationFilterAttributes(operation, context);
     ApplyResponseRemoveDefaultsAttributes(operation, context);
     ApplyResponseAttributes(operation, context);
 }
        public void Apply(Operation operation, OperationFilterContext context)
        {
            // Correspond each "Authorize" role to an oauth2 scope
            var controllerScopes = context.ApiDescription.GetControllerAttributes()
                .OfType<AuthorizeAttribute>()
                .SelectMany(attr => attr.Roles.Split(','));

            var actionScopes = context.ApiDescription.GetActionAttributes()
                .OfType<AuthorizeAttribute>()
                .SelectMany(attr => attr.Roles.Split(','));

            var scopes = controllerScopes.Union(actionScopes).Distinct();

            if (scopes.Any())
            {
                if (operation.Security == null)
                    operation.Security = new List<IDictionary<string, IEnumerable<string>>>();

                var oAuthRequirements = new Dictionary<string, IEnumerable<string>>
                {
                    { "oauth2", scopes }
                };

                operation.Security.Add(oAuthRequirements);
            }
        }
 private static void ApplyResponseRemoveDefaultsAttributes(Operation operation, OperationFilterContext context)
 {
     var apiDesc = context.ApiDescription;
     if (apiDesc.GetControllerAttributes().OfType<SwaggerResponseRemoveDefaultsAttribute>().Any() ||
         apiDesc.GetActionAttributes().OfType<SwaggerResponseRemoveDefaultsAttribute>().Any())
     {
         operation.Responses.Clear();
     }
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="context"></param>
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null) return;

            foreach (IParameter param in operation.Parameters)
            {
                if (param.In == "modelbinding")
                    param.In = "query";
            }
        }
        private static void ApplyResponseAttributes(Operation operation, OperationFilterContext context)
        {
            var apiDesc = context.ApiDescription;
            var attributes =
                apiDesc.GetControllerAttributes().OfType<SwaggerResponseAttribute>()
                .Union(apiDesc.GetActionAttributes().OfType<SwaggerResponseAttribute>())
                .OrderBy(attr => attr.StatusCode);

            foreach (var attribute in attributes)
                ApplyResponseAttribute(operation, context, attribute);
        }
        public static void ApplyOperationFilterAttributes(Operation operation, OperationFilterContext context)
        {
            var apiDesc = context.ApiDescription;

            var controllerAttributes = apiDesc.GetControllerAttributes().OfType<SwaggerOperationFilterAttribute>();
            var actionAttributes = apiDesc.GetActionAttributes().OfType<SwaggerOperationFilterAttribute>();

            foreach (var attribute in controllerAttributes.Union(actionAttributes))
            {
                var filter = (IOperationFilter)Activator.CreateInstance(attribute.FilterType);
                filter.Apply(operation, context);
            }
        }
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (operation.OperationId.Contains("Token"))
            {
                operation.Consumes.Add("application/x-www-form-urlencoded");

                foreach(var parameter in operation.Parameters)
                {
                    parameter.In = "formData";
                }
            };

            string actionName = ((ControllerActionDescriptor)context.ApiDescription.ActionDescriptor).ActionName;
            operation.OperationId = $"{context.ApiDescription.GroupName}_{actionName}";
        }
        private static void ApplyResponseAttribute(
            Operation operation,
            OperationFilterContext context,
            SwaggerResponseAttribute attribute)
        {
            var statusCode = attribute.StatusCode.ToString();

            operation.Responses[statusCode] = new Response
            {
                Description = attribute.Description ?? InferDescriptionFrom(statusCode),
                Schema = (attribute.Type == null)
                    ? null
                    : context.SchemaRegistry.GetOrRegister(attribute.Type)
            };
        }
        private static void ApplyOperationAttributes(Operation operation, OperationFilterContext context)
        {
            var attribute = context.ApiDescription.GetActionAttributes()
                .OfType<SwaggerOperationAttribute>()
                .FirstOrDefault();
            if (attribute == null) return;

            if (attribute.OperationId != null)
                operation.OperationId = attribute.OperationId;

            if (attribute.Tags != null)
                operation.Tags = attribute.Tags;

            if (attribute.Schemes != null)
                operation.Schemes = attribute.Schemes;
        }
        public void Apply(Operation operation, OperationFilterContext context)
        {
            var controllerActionDescriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor;
            if (controllerActionDescriptor == null) return;

            var methodXPath = GetMethodXPath(controllerActionDescriptor.MethodInfo);
            var methodNode = _xmlNavigator.SelectSingleNode(methodXPath);
            if (methodNode == null) return;

            var summaryNode = methodNode.SelectSingleNode(SummaryExpression);
            if (summaryNode != null)
                operation.Summary = summaryNode.ExtractContent();

            var remarksNode = methodNode.SelectSingleNode(RemarksExpression);
            if (remarksNode != null)
                operation.Description = remarksNode.ExtractContent();

            ApplyParamComments(operation, methodNode);
        }
        public void Apply(Operation operation, OperationFilterContext context)
        {
            var controllerActionDescriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor;
            if (controllerActionDescriptor == null) return;

            var commentId = XmlCommentsIdHelper.GetCommentIdForMethod(controllerActionDescriptor.MethodInfo);
            var methodNode = _xmlNavigator.SelectSingleNode(string.Format(MemberXPath, commentId));
            if (methodNode == null) return;

            var summaryNode = methodNode.SelectSingleNode(SummaryTag);
            if (summaryNode != null)
                operation.Summary = summaryNode.ExtractContent();

            var remarksNode = methodNode.SelectSingleNode(RemarksTag);
            if (remarksNode != null)
                operation.Description = remarksNode.ExtractContent();

            ApplyParamComments(operation, methodNode);
        }
 public void Apply(Operation operation, OperationFilterContext context)
 {
     operation.Extensions.Add("x-purpose", "test");
 }
        public void Apply(Operation operation, OperationFilterContext context)
        {
            var remove = operation.Parameters
                ?.Where(x => x.In == "modelbinding")
                ?.ToArray();
            if (remove == null) return;

            foreach (var param in remove) {
                operation.Parameters.Remove(param);
            }

            var Params = context.ApiDescription.ParameterDescriptions
                .Where(x => x.ModelMetadata?.ContainerType == null)
                .Select(x => x.Name);

            var Remove = context.ApiDescription.ParameterDescriptions
                .Select(x => x.Name).Except(Params);
            foreach (var param in Remove) {
                var item = operation.Parameters?.Where(x => x.Name == param).FirstOrDefault();
                if (item == null) continue;
                operation.Parameters.Remove(item);
            }

            #region fix parameter
            var doubleParam = operation.Parameters.GroupBy(x => x.Name).Where(x => x.Count() > 1);
            foreach (var param in doubleParam) {
                var item = operation.Parameters
                    ?.Where(
                        x => x.Name.ToUpper() == param.Key.ToUpper() && x.In != "path"
                        ).LastOrDefault();
                if (item == null) continue;
                operation.Parameters.Remove(item);
            }
            #endregion

            #region fix files upload
            if (operation.OperationId == "ApiFileByTargetPost") {
                var parameter = (NonBodyParameter)operation.Parameters
                    .Where(x => x.Name == "files").SingleOrDefault();

                parameter.Type = "file";
            }
            #endregion

            #region fix formData Bug
            foreach (var param in operation.Parameters) {
                if (param.In == "form") {
                    param.In = "formData";
                }
            }
            #endregion

            var attrs = context.ApiDescription.GetActionAttributes();
            var auth = (AuthorizeAttribute)attrs.Where(x => x is AuthorizeAttribute).SingleOrDefault();
            if (auth != null) {
                List<string> Tags = new List<string>(operation.Tags);
                if (auth.Policy == "AdminOnly") {
                    Tags.Add("AdminOnly");
                } else {
                    Tags.Add("LoginOnly");
                }
                operation.Tags = Tags;
            }
        }
 public void Apply(Operation operation, OperationFilterContext contex)
 {
     operation.Extensions.Add("X-property1", "value");
 }
Exemple #16
0
        private Operation CreateOperation(ApiDescription apiDescription, ISchemaRegistry schemaRegistry)
        {
            var groupName = _options.GroupNameSelector(apiDescription);

            var parameters = apiDescription.ParameterDescriptions
                .Where(paramDesc => paramDesc.Source.IsFromRequest)
                .Select(paramDesc => CreateParameter(paramDesc, schemaRegistry))
                .ToList();

            var responses = new Dictionary<string, Response>();
            if (apiDescription.ResponseType == typeof(void))
                responses.Add("204", new Response { Description = "No Content" });
            else
                responses.Add("200", CreateSuccessResponse(apiDescription.ResponseType, schemaRegistry));

            var operation = new Operation
            {
                Tags = (groupName != null) ? new[] { groupName } : null,
                OperationId = apiDescription.FriendlyId(),
                Produces = apiDescription.Produces().ToList(),
                //consumes = apiDescription.Consumes().ToList(),
                Parameters = parameters.Any() ? parameters : null, // parameters can be null but not empty
                Responses = responses,
                Deprecated = apiDescription.IsObsolete()
            };

            var filterContext = new OperationFilterContext(apiDescription, schemaRegistry);
            foreach (var filter in _options.OperationFilters)
            {
                filter.Apply(operation, filterContext);
            }

            return operation;
        }