Reputation: 1110
I really need to know how i can pass a token to WCF service without adding an extra parameter to all my contracts, some value like a number so that i can use it later on my services.
Upvotes: 1
Views: 3015
Reputation: 45272
This problem is solved using custom headers.
You can assign a custom header to your client like so:
IContextChannel contextChannel = (IContextChannel)myServiceProxy;
using (OperationContextScope scope = new OperationContextScope(contextChannel))
{
MessageHeader header = MessageHeader.CreateHeader("PlayerId", "", _playerId);
OperationContext.Current.OutgoingMessageHeaders.Add(header);
act(service);
}
On the service side you can get this value:
private long ExtractPlayerIdFromHeader()
{
try
{
var opContext = OperationContext.Current;
var requestContext = opContext.RequestContext;
var headers = requestContext.RequestMessage.Headers;
int headerIndex = headers.FindHeader("PlayerId", "");
long playerId = headers.GetHeader<long>(headerIndex);
return playerId;
}
catch (Exception ex)
{
this.Log.Error("Exception thrown when extracting the player id from the header", ex);
throw;
}
}
Also see this question for how you can set the custom headers via a configuration file.
Upvotes: 2
Reputation: 181097
One way would be to use WCFExtras and put the value in a soap header.
[SoapHeader("MyToken", typeof(Header), Direction = SoapHeaderDirection.In)]
[OperationContract]
string In();
That would make the token obvious in the WSDL in case it's required for the service's operation.
Another option is to use HTTP headers, which you can do without attributing your methods at all. The downside to that is that the token does not show up in the WSDL, so the service is no longer completely described by the WSDL.
Upvotes: 2