【问题标题】:IDispatchMessageInspector CorrelationState, and accessing it in betweenIDispatchMessageInspector CorrelationState,并在两者之间访问它
【发布时间】:2019-05-18 19:05:43
【问题描述】:

我的 AfterRecieveRequest 方法生成一个 GUID,并通过correlationState 变量将其传递给 BeforeSendReply 方法。

在这两个调用之间,我的 WCF 服务中发生了很多事情,我想从 Web 服务方法中访问这个 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 保存在内存中的某个位置,但恐怕我对这个主题的理解不足以现在实现它。

【问题讨论】:

  • 不言而喻,我已尽力隐藏不相关的代码,但如果我出于某种原因遗漏了您需要帮助我的内容,请告诉我。
  • 您将使用“当前”对象并将correlationState(或您希望在逻辑请求期间可用的任何内容)存储在其中。有关示例,请参见 this answer

标签: c# .net wcf idispatchmessageinspector


【解决方案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;
    }
}

【讨论】:

  • 感谢您的回答。我已经通过将 GUID 作为标题添加到传入消息中解决了我的问题,因为无论如何我已经在使用 OperationContext,但是您的解决方案似乎更好,因此我已将您的回复标记为答案。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多