首页 > 解决方案 > Swashbuckle 仅向某些方法添加自定义标头

问题描述

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

启动.cs

public void ConfigureServices(IServiceCollection services)
{
    
    services.AddSwaggerGen(c =>
    {
        // some swagger services here.
        c.OperationFilter<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-coreswagger

解决方案


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

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"
            }
        });
    }

}

我希望这会对你们有所帮助。


推荐阅读