问题
I am using WCF Services for my application. I've got three functions - Add, GetList, GetSingle.
To create the service on the client-side, I am using this code:
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
will return a string containing a GUID.
On server-side, I am retrieving the data using this:
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
When I call the Add or the GetList function, the incoming header is being well retrieved. However, when I am calling the GetSingle function, the incoming header is always empty. Note that the same code is being used to create the service in all three methods, as well as to retrieve the wanted header.
I am lost about the reason that one of the three functions is not behaving like the others, while the same code is being executed. What could possibly be the reason for not being able to retrieve the information?
回答1:
In my opinion, the above code on the client-side didn’t work. the OperationContext.Current will always return null. Ordinarily, we manage to get the OperationContext.current instance only within the OperationContextScope, like below.
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);
The scope of OperationContextScope is only valid within the using statement. After the instance of OperationContextScope is released, the OperationContext is restored and the message header is no longer valid. If we call the method inside the using statement, we are capable of finding the custom header on the server-side.
We can use the IClientMessageInspector interface if we want to permanently add message headers to every requests.
https://putridparrot.com/blog/adding-data-to-wcf-message-headers-client-side/
Feel free to let me know if there is anything I can help with.
来源:https://stackoverflow.com/questions/57360098/adding-an-outgoing-message-headers-in-wcf-cant-be-retrieved-in-incoming-message