Yarons 的评论让我朝着正确的方向前进
ParameterInspector 提取值并使用自定义 operationContext 扩展将其放置到 operationContext
public class TestParameterInspector : IParameterInspector
{
public object BeforeCall(string operationName, object[] inputs)
{
return null;
}
public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
{
OperationContext.Current.Extensions.Add(new ContextSessionExtension() {SomeData = "testme"} );
}
}
public class ContextSessionExtension : IExtension<OperationContext>
{
public void Attach(OperationContext owner)
{
}
public void Detach(OperationContext owner)
{
}
public string SomeData { get; set; }
}
然后使用 MessageInspector 将值提取并放入 HTTP 标头中
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
return null;
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
}
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
return null;
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
var test = OperationContext.Current.Extensions.Find<ContextSessionExtension>().SomeData;
object httpRequestMessageObject;
HttpRequestMessageProperty httpRequestMessage;
if (reply.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
{
httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
if (string.IsNullOrEmpty(httpRequestMessage.Headers["MYTEST"]))
{
httpRequestMessage.Headers["MYTEST"] = test;
}
}
else
{
httpRequestMessage = new HttpRequestMessageProperty();
httpRequestMessage.Headers.Add("MYTEST", test);
reply.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
}
}