提问人:Paul Karam 提问时间:8/5/2019 最后编辑:Paul Karam 更新时间:8/6/2019 访问量:2351
无法在传入邮件头中检索 WCF 中的传出邮件头
Adding an outgoing message headers in WCF can't be retrieved in incoming message headers
问:
我正在将 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 函数时,传入标头始终为空。请注意,在所有三种方法中创建服务以及检索所需的标头都使用相同的代码。
我不明白为什么这三个函数中的一个在执行相同的代码时表现得不像其他函数。无法检索信息的原因可能是什么?
答:
在我看来,客户端的上述代码不起作用。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/ 如果有什么我可以帮忙的,请随时告诉我。
评论