我们正在使用带有Swagger的WebApi服务器来记录端点。我们想要添加Content-Security-Policy和X-Frame-Options标头。我们希望通过拦截调用并添加自定义标头来实现此目的,但是我们无法找到这样做的方法。我们使用Swashbuckle Swagger for WebApi NuGet包5.0.4版本。
有没有办法拦截Swagger响应或任何方式为响应添加自定义标头?
答案 0 :(得分:4)
如果您想将标题添加到所有回复,则可以选择添加DelegatingHandler
,以便通过覆盖SendAsync
方法添加标题。因此,您将创建一个继承自DelegatingHandler
的类,然后重写SendAsync
。 e.g:
public class AddCustomHeadersResponseHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
response.Headers.Add("Content-Security-Policy", "yourSecurityValue");
response.Headers.Add("X-Frame-Options", "yourFrameOptions");
return response;
}
}
然后在Global.asax.cs的Application_Start()
中将该类的实例添加到您的配置中:
GlobalConfiguration.Configuration.MessageHandlers.Add(new AddCustomHeadersResponseHandler());