IDispatchMessageInspector CorrelationState,并在两者之间访问它

IDispatchMessageInspector CorrelationState, and accessing it in between

我的 AfterRecieveRequest 方法生成一个 GUID,并通过 correlationState 变量将其传递给 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 保存在内存中的某个位置,但恐怕我对这个主题的理解不足以立即实现它。

不确定这是否是您想要的,但您可以将 GUID 添加到您的频道消息中 header。有人已经写了一些有用的信息:https://whosebug.com/a/1408177/2016162

如果您只想访问 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;
    }
}