【发布时间】:2020-03-10 10:33:30
【问题描述】:
我有一个独立的 C# WCF 服务作为 Windows 服务运行。我需要向所有响应添加自定义标头,例如 X-Frame-Options。我试图将以下类的实例添加到ServiceEndpoint.Behaviors
internal class ServerInterceptor : IDispatchMessageInspector, IEndpointBehavior
{
object IDispatchMessageInspector.AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
return null;
}
void IDispatchMessageInspector.BeforeSendReply(ref Message reply, object correlationState)
{
reply.Properties.Add("X-Frame-Options", "deny");
}
void IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this);
}
void IEndpointBehavior.Validate(ServiceEndpoint endpoint) { }
void IEndpointBehavior.AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { }
void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) { }
}
这不会向响应中添加任何 HTTP 标头,尽管由于调试器可以单步执行 BeforeSendReply 函数而调用了该类。此外,如果我将 reply.Properties 替换为 reply.Headers 则会添加标头,但不会添加到 HTTP 标头,而是添加到 SOAP 标头。
如何在响应中添加像 X-Frame-Options 这样的 HTTP 标头?
【问题讨论】:
-
你试过
HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty(); requestMessage.Headers["X-Frame-Options"] = "deny"; OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;吗? -
我还发现了这段代码 sn-p 并且它不起作用(确切地说是不起作用),因为没有“X-Frame-Options”标头。