我已经在WCF上实现了Proto-buf.net,我的WCF服务现在使用它作为他们的序列化器,到目前为止都很好。
但是,我需要将消息中的一些信息添加到HTTP标头中,以便可以在网络中跟踪这些数据包。
我已经实现了一个Message Inspector,允许我添加Header信息,但是此时消息已经通过proto-buf序列化器运行,不再可读。
是否可以在序列化之前拦截消息并仍然可以访问HttpRequestMessage标头?如果没有,我可以在消息检查员可以访问的地方放置一些有关请求的信息吗?
非常感谢
答案 0 :(得分:0)
Yarons评论让我朝着正确的方向前进
ParameterInspector拉出值并使用cusom 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);
}
}