WCF自动添加消息头

时间:2025-01-20 11:06:20

客户端自定义消息查看器实现IClientMessageInspector接口在消息发送之前添加消息头

class ClientMessageInspector : System.ServiceModel.Dispatcher.IClientMessageInspector, System.ServiceModel.Description.IEndpointBehavior
{
public Dictionary<string, string> HeaderValue { get; set; } #region Implementation for IClientMessageInspector
public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState) { } public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
{
if (HeaderValue != null)
{
foreach (var v in HeaderValue)
{
request.Headers.Add(System.ServiceModel.Channels.MessageHeader.CreateHeader(v.Key, "client", v.Value));
}
} return null;
}
#endregion #region Implementation for IEndpointBehavior
public void AddBindingParameters(System.ServiceModel.Description.ServiceEndpoint serviceEndpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) { } public void ApplyClientBehavior(System.ServiceModel.Description.ServiceEndpoint serviceEndpoint, ClientRuntime behavior)
{
//此处为Extension附加到ClientRuntime。
behavior.MessageInspectors.Add(this);
} public void ApplyDispatchBehavior(System.ServiceModel.Description.ServiceEndpoint serviceEndpoint, EndpointDispatcher endpointDispatcher)
{
//如果是扩展服务器端的MessageInspector,则要附加到EndpointDispacther上了。
//endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this);
} public void Validate(System.ServiceModel.Description.ServiceEndpoint serviceEndpoint) { }
#endregion
}
//添加消息头
client.ChannelFactory.Endpoint.Behaviors.Add(new ClientMessageInspector()
{
HeaderValue = new Dictionary<string, string>() {
{"OrganID", GetAppSetting("OrganID")},
{"HandshakeCode", GetAppSetting("HandshakeCode")}
}
});

服务器端获取消息头

private string GetHeaderValue(string name)
{
var headers = OperationContext.Current.IncomingMessageHeaders;
var index = headers.FindHeader(name, "client");
if (index > -1)
{
return headers.GetHeader<string>(index);
} return string.Empty;
}