使用MessageInspector
向客户端的每个WCF调用添加自定义标头时,在服务器端的AfterReceiveRequest
方法中获取自定义标头项后,在哪里保留自定义标头项?我希望以后能够在WCF服务器代码中访问它们。自定义标题项将是从客户端发送的会话号。
public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
{
int headerIndex = request.Headers.FindHeader("SessionID", string.Empty);
if (headerIndex != -1)
{
// where to keep the custom header item?
}
return null;
}
答案 0 :(得分:0)
您可以使用OperationContext.Current
示例:
public string GetData(int value)
{
var headers = OperationContext.Current.IncomingMessageHeaders;
int headerIndex = headers.FindHeader("SessionID", string.Empty);
...
}
如果您担心单元测试,只需在提供者/服务中包装OperationContext.Current。
示例:
public class Service1 : IService1
{
private ISessionInspector _sessionInspector; //will access OperationContext.Current
public Service1(ISessionInspector sessionInspector)
{
_sessionInspector = sessionInspector;
}
public string GetData(int value)
{
var sessionId = _sessionInspector.GetCurrentSessionID();
...
}