In WCF, headers can be accessed through an instance of the OperationContext class , which is accessible through OperationContext.Current (if available).
The naive way to approach this problem is to simply use this property in your service method:
[ServiceContract]
public interface IMyService
{
[OperationContract]
void MyMethod();
}
internal class MyService: IMyService
{
public void MyMethod()
{
Console.WriteLine("My Method");
OperationContext.Current.OutgoingMessageHeaders.Add(MessageHeader.CreateHeader("headerFromMethod", "namespace", "headerFromMethodValue"));
}
}
, ( ):
using (var serviceHost = new ServiceHost(typeof(MyService)))
{
var endpoint = serviceHost.AddServiceEndpoint(typeof(IMyService), new BasicHttpBinding(), "http://localhost:9000");
serviceHost.Open();
Console.WriteLine("Open for business");
Console.ReadLine();
serviceHost.Close();
}
.NET :
var channel = ChannelFactory<IMyService>.CreateChannel(new BasicHttpBinding(), new EndpointAddress("http://localhost:9000"));
var contextChannel = channel as IContextChannel;
using (new OperationContextScope(contextChannel))
{
channel.MyMethod();
var incommingHeaders = OperationContext.Current.IncomingMessageHeaders;
var header = incommingHeaders.GetHeader<string>("headerFromMethod", "namespace");
Console.WriteLine("Header from server: " + header);
}
Fiddler, , .
, , , - ( IMyService) , "" , .
IDispatchMessageInspector, :
public 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.Headers.Add(MessageHeader.CreateHeader("header", "namespace", "headervalue"));
}
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){}
}
.NET- , . , AfterReceiveRequest BeforeSendReply, , , correlationState . , - .
, , :
...
var endpoint = serviceHost.AddServiceEndpoint(typeof(IMyService), new BasicHttpBinding(), "http://localhost:9000");
endpoint.Behaviors.Add(new ServerInterceptor());
serviceHost.Open();
...
, ServerInterceptor IEndpointBehavior