【问题标题】:Fetching MessageId from IParameterInspector从 IParameterInspector 获取 MessageId
【发布时间】:2013-11-29 15:50:09
【问题描述】:

作为我的 WCF 服务的一部分,我想使用请求的操作和提供的输入参数来记录传入/传出呼叫。

我还想在 same 日志行中记录请求的 MessageIdIParameterInspector 看起来很适合这个,但是 MessageId(消息请求对象的一部分)在这里不可用。

如果我实现IDispatchMessageInspector,我可以访问 Message 对象,但不能访问输入参数/操作(从技术上讲,我可以,但获取它们并非易事)。我真的很想使用IParameterInspectorBeforeCall 功能,因为它不需要对消息架构进行任何假设。

我可能遗漏了一些非常简单的东西,但是在同一范围内获得 both MessageId 和输入参数似乎并不容易。

结合BeforeCallBeforeSendRequest,或者至少在这两种方法之间传递数据,将是完美的。

【问题讨论】:

    标签: c# wcf logging serialization


    【解决方案1】:

    你可以在你的 IParameterInspector 中使用类似的东西:

    OperationContext.Current.IncomingMessageHeaders.MessageId
    

    【讨论】:

    • 这个我试过了,可惜OperationContext.Current在BeforeCall的范围内为null。
    • 这很奇怪。应该已经设置好了。你的配置是什么?
    • 可能是因为我在本地运行客户端?我目前正在调试客户端-> WCF。在客户端使用 null OperationContext.Current 属性调用 BeforeCall。无特殊配置——其实在 AfterCall 中也是 null ......
    • 哎呀。经过一番调试,如果在多线程环境中使用,似乎 OperationContext.Current 不可用。我的客户端产生了多个访问服务器的线程,因此我看到 null。我想避免向服务实现本身添加代码(例如设置线程静态)并理想地处理端点行为中的所有内容,但这似乎并不简单:(。
    • 如果您直接创建服务类型的实例 - 而不是 WCF 代理/客户端通道 - 然后在其上调用方法,则没有 OperationContext。当您的操作在服务中运行时,WCF 会提供一个 OperationContext 实例。
    【解决方案2】:

    请参考链接WCF Unique ID for each service method call

    另一种选择是在 afterRecieveRequest 中添加消息属性

    public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
           {
    
    Guid activityId = Guid.NewGuid();
                System.ServiceModel.OperationContext.Current.IncomingMessageProperties.Add("LOGID", activityId);
    //log your messages here
    
    return activityId 
    
    }
    
    public void BeforeSendReply(ref Message reply, object correlationState)
           {
                Guid activityId = (Guid)correlationState;
    //Log your Message here..
    }
    

    在为请求提供服务的实际函数中,您可以访问此属性

     public String SayHello(String request)
                {
                    object activityId;
                    System.ServiceModel.OperationContext.Current.IncomingMessageProperties.TryGetValue("LOGID", out activityId);
    
        //log your messages here with this ID....
    
    Return "Hello, World";
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-15
      • 1970-01-01
      • 2011-12-04
      • 1970-01-01
      • 2023-03-28
      • 2020-07-04
      • 2018-01-25
      • 1970-01-01
      相关资源
      最近更新 更多