【问题标题】:Adding an outgoing message headers in WCF can't be retrieved in incoming message headers无法在传入邮件标头中检索在 WCF 中添加传出邮件标头
【发布时间】:2019-12-13 01:35:08
【问题描述】:

我正在为我的应用程序使用 WCF 服务。我有三个函数 - Add、GetList、GetSingle。

要在客户端创建服务,我使用以下代码:

Public Shared Function GetService(ByRef oScope As OperationContextScope) As XService.XServiceClient
    Dim oService As New XService.XServiceClient
    oScope = New OperationContextScope(oService.InnerChannel)
    oService.Open()
    Dim oMessageHeader As System.ServiceModel.Channels.MessageHeader = MessageHeader.CreateHeader("SecurityContext", String.Empty, AuthenticationModule.GetAuthenticationTicketToService)
    OperationContext.Current.OutgoingMessageHeaders.Add(oMessageHeader)
    Return oService
End Function

AuthenticationModule.GetAuthenticationTicketToService 将返回一个包含 GUID 的字符串。

在服务器端,我正在使用以下方法检索数据:

Public Function GetTokenValue() As String
    If OperationContext.Current.IncomingMessageHeaders.FindHeader("SecurityContext", "") <> -1 Then
        Return OperationContext.Current.IncomingMessageHeaders.GetHeader(Of String)("SecurityContext", "")
    End If
    Return ""
End Function

当我调用 Add 或 GetList 函数时,正在很好地检索传入的标头。但是,当我调用 GetSingle 函数时,传入的标头始终为空。请注意,在所有三种方法中都使用相同的代码来创建服务,以及检索所需的标头。

我对三个函数之一的行为与其他函数不同的原因感到迷茫,而正在执行相同的代码。无法检索信息的可能原因是什么?

【问题讨论】:

    标签: .net vb.net wcf http-headers wcf-client


    【解决方案1】:

    在我看来,上面的客户端代码不起作用。 OperationContext.Current 将始终返回 null。通常,我们只能在 OperationContextScope 中获取 OperationContext.current 实例,如下所示。

      using (OperationContextScope ocs = new OperationContextScope(client.InnerChannel);)
                {
                    MessageHeader header = MessageHeader.CreateHeader("myname", "mynamespace", "myvalue");
                    OperationContext.Current.OutgoingMessageHeaders.Add(header);
                    var result = client.GetData();
                    Console.WriteLine(result);
                }
    //this call would not add the custom header
                var result2 = client.GetData();
                Console.WriteLine(result2);
    

    OperationContextScope 的作用域只在 using 语句内有效。 OperationContextScope实例释放后,OperationContext恢复,消息头不再有效。如果我们在 using 语句中调用该方法,我们就能够在服务器端找到自定义标头。
    如果我们想为每个请求永久添加消息头,我们可以使用 IClientMessageInspector 接口。
    https://putridparrot.com/blog/adding-data-to-wcf-message-headers-client-side/
    如果有什么可以帮助的,请随时告诉我。

    【讨论】:

    • 我最终使用了 IClientMessageInspector 并且它有效。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2017-04-09
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 2012-05-10
    • 2022-11-16
    • 2017-03-09
    相关资源
    最近更新 更多