简体   繁体   中英

Passing a token to WCF service

我真的需要知道如何在不向我的所有合同添加额外参数的情况下将令牌传递给WCF服务,某些值就像一个数字,以便我以后可以在我的服务上使用它。

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM