无法在传入消息 headers 中检索在 WCF 中添加传出消息 headers

Adding an outgoing message headers in WCF can't be retrieved in incoming message headers

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

要在 client-side 上创建服务,我正在使用此代码:

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 将 return 包含 GUID 的字符串。

在 server-side,我正在使用此检索数据:

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 函数时,正在很好地检索传入的 header。但是,当我调用GetSingle 函数时,传入的header 始终为空。请注意,相同的代码用于在所有三种方法中创建服务,以及检索想要的 header.

我不知道为什么三个函数中的一个在执行相同的代码时表现得不像其他函数。无法检索信息的原因可能是什么?

在我看来,client-side 上的上述代码无效。 OperationContext.Current 将始终 return 为空。通常,我们设法仅在 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恢复,消息header不再有效。如果我们在 using 语句中调用该方法,我们能够在 server-side.
上找到自定义 header 如果我们想向每个请求永久添加消息 headers,我们可以使用 IClientMessageInspector 接口。
https://putridparrot.com/blog/adding-data-to-wcf-message-headers-client-side/
如果有什么我可以帮忙的,请随时告诉我。