我的AfterRecieveRequest方法生成一个GUID,并将其通过relatedState变量传递给BeforeSendReply方法。
在这两个调用之间,我的WCF服务中发生了很多事情,我想从Webservice方法中访问此GUID。我有办法在整个WCF服务中访问此对象吗?
GUID用于记录目的,因为我正在调用其他应用程序的API,并希望记录结果,并将结果记录在IDispatchMessageInspector实现中生成的GUID下。
例如:
IDispatchMessageInspector实现:
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
var correlationState = GUID.NewGuid();
StaticLogger.AddLog(originalMessage, correlationState.ToString(), "WCF-Incoming");
return correlationState;
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
StaticLogger.AddLog(originalMessage, correlationState.ToString(), "WCF-Outgoing");
}
WCF服务:
public ResponseObject WCFMethod(string param1, string param2)
{
ResponseObject response = new ResponseObject();
Client client = new Client();
ClientObject result = client.OutsideOperation(param1,param2);
// here, i would like to log the result object and use the GUID from the correlationstate
StaticLogger.AddLog(result, correlationState.ToString(), WCF-Internal )
response.resultAttribute = result;
return response;
}
我将如何继续做到这一点?我一直在考虑使用ThreadStatic属性,以便线程将GUID保留在内存中的某个位置,但是我对这个问题的理解不足以立即实现它。
答案 0 :(得分:1)
如果您只想访问BeforeSendReply和AfterReceiveRequest之间的GUID, 您可以使用MessageProperties,在执行服务时可以访问MessageProperties。
下面是我的测试。
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
var correlationState = Guid.NewGuid();
request.Properties["myGuid"] = correlationState; // store guid in Properties
return correlationState;
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
}
然后,您就可以在服务中获取GUID。
public class ServiceTest : Test
{
public double add(double a, double b)
{
// get the property through IncomingMessageProperties property
Guid gu = (Guid)OperationContext.Current.IncomingMessageProperties["myGuid"];
Console.WriteLine(gu);
return a + b;
}
}
答案 1 :(得分:0)
不确定这将是您想要的,但是您可以将GUID添加到频道消息头中。有人已经写了一些有用的信息:https://stackoverflow.com/a/1408177/2016162