【问题标题】:Swashbuckle add custom header to some methods onlySwashbuckle 仅向某些方法添加自定义标头
【发布时间】:2021-04-09 13:38:04
【问题描述】:

我已经在我的 .net 核心应用程序中使用 IOperationFilter 成功添加了自定义标头,现在我的问题是如何仅在 SomeController 类中为某些方法过滤掉它。这是可以实现的吗?这是我当前的代码:

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    
    services.AddSwaggerGen(c =>
    {
        // some swagger services here.
        c.OperationFilter<SomeFilter>();
    });
}

SomeFilter.cs

public class SomeFilter: IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        if (operation.Parameters == null)
                operation.Parameters = new List<OpenApiParameter>();

        operation.Parameters.Add(new OpenApiParameter
        {
            Name = "Some-Custom-Header",
            In = ParameterLocation.Header,
            Required = false,
            Schema = new OpenApiSchema
            {
                Type = "String"
            }
        });
    }

}

SomeController.cs

[ApiController]
[Route("[controller]")]
public class SomeController: Controller
{
    [AllowAnonymous]
    [HttpPost("some_method1")]
    public IAction SomeMethod1() // this method should not include custom header filter
    {
        return Ok();
    }
    
    [Authorize]
    [HttpPost("some_method2_with_authorize")]
    public IAction SomeMethod2() // this should have the custom header in swagger
    {
        return Ok();
    }

    [AllowAnonymous]
    [HttpGet("some_method3_without_authorize")]
    public IAction SomeMethod3() // this should have the custom header in swagger
    {
        return Ok();
    }

}

【问题讨论】:

    标签: c# asp.net-core swagger


    【解决方案1】:

    我找到了一种方法来排除将排除上述方法的方法:

    public class SomeFilter: IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            var methodName = context.ApiDescription.ActionDescriptor.As<ControllerActionDescriptor>().ActionName;
            var hasExcludedMethod = ApiFilterSettings.AppSettingsFilterMethods.ToStringList().Contains(methodName);
            if(hasExcludedMethod)
               return; // return directly when an excluded method is found;**strong text**
    
            if (operation.Parameters == null)
                    operation.Parameters = new List<OpenApiParameter>();
    
            operation.Parameters.Add(new OpenApiParameter
            {
                Name = "Some-Custom-Header",
                In = ParameterLocation.Header,
                Required = false,
                Schema = new OpenApiSchema
                {
                    Type = "String"
                }
            });
        }
    
    }
    

    希望对大家有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-24
      • 1970-01-01
      • 1970-01-01
      • 2019-09-12
      • 2019-02-19
      • 2012-11-15
      • 1970-01-01
      • 2020-08-24
      相关资源
      最近更新 更多