.NET Core中使用Swashbuckle的IOperationFilter时,如何排除SomeController中的特定接口方法不添加自定义请求头
当然可以实现这个需求!我们可以通过自定义一个标记特性(Attribute),配合在IOperationFilter里做判断来精准跳过特定接口方法的自定义请求头添加逻辑。下面是具体的实现步骤:
1. 创建自定义跳过特性
首先定义一个专门用来标记不需要添加自定义请求头的方法特性:
[AttributeUsage(AttributeTargets.Method)] public class SkipCustomHeaderAttribute : Attribute { // 无需额外逻辑,仅作为标记使用 }
2. 修改SomeFilter添加判断逻辑
在你的IOperationFilter实现中,通过OperationFilterContext拿到当前接口方法的MethodInfo,检查是否带有上面定义的标记特性,如果有就直接跳过添加请求头的操作:
public class SomeFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { // 检查当前方法是否标记了SkipCustomHeaderAttribute,是则跳过 var shouldSkip = context.MethodInfo .GetCustomAttributes(typeof(SkipCustomHeaderAttribute), inherit: false) .Any(); if (shouldSkip) { return; } 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" // 注意OpenAPI规范中类型名称为小写的string } }); } }
3. 在目标方法上添加标记
最后只需要在你想要排除的接口方法(比如SomeMethod1)上加上[SkipCustomHeader]特性即可:
[ApiController] [Route("[controller]")] public class SomeController : Controller { [AllowAnonymous] [SkipCustomHeader] // 标记该方法跳过自定义请求头 [HttpPost("some_method1")] public IActionResult SomeMethod1() { // 该方法不应添加自定义请求头过滤器 return Ok(); } [Authorize] [HttpPost("some_method2_with_authorize")] public IActionResult SomeMethod2() { // 该方法应在Swagger中显示自定义请求头 return Ok(); } [AllowAnonymous] [HttpGet("some_method3_without_authorize")] public IActionResult SomeMethod3() { // 该方法应在Swagger中显示自定义请求头 return Ok(); } }
这样一来,只有没有标记[SkipCustomHeader]的方法才会在Swagger中显示Some-Custom-Header请求头,完全满足你的需求。这种方式的好处是灵活性很高,后续想要调整哪些方法需要跳过,只需要添加/移除特性即可,不需要修改过滤器的核心逻辑。
内容的提问来源于stack exchange,提问作者Alvin Quezon
相关产品推荐
相关产品推荐

