1

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

4

2 回答 2

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)
    {

    }

然后,您可以获得服务中的指南。

 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;
    }
}
于 2018-12-27T06:35:45.153 回答
0

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

于 2018-12-18T16:07:58.057 回答