c# - 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();
}
}
解决方案
我找到了一种方法来排除将排除上述方法的方法:
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"
}
});
}
}
我希望这会对你们有所帮助。
推荐阅读
- java - 简单 for 循环上的 Java vs C++ 速度
- flutter - 检测小部件是否溢出
- python - TypeError:('关键字参数不理解:','子样本')
- ios - iOS - 如何在使用自定义 UIBezierPath 绘制的 CAShapeLayer 中设置 CATextLayer?
- powershell - 如何在 import vapp 命令中使用哈希表键值和数组?
- android - 禁用 HideBottomViewOnScrollBehaviour
- nginx - 为同一服务器上的多个应用程序配置 Nginx 的问题
- java - 将 Java 类型映射到数据库类型
- java - session.setAttribute 没有给出选定的值
- javascript - slideUp/slideDown 动画仅在一个部分中