Skip to main content
 首页 » 编程设计

c#之将 token 传递给 WCF 服务

2024年02月13日14pengyingh

我真的需要知道如何在不向我的所有契约(Contract)添加额外参数的情况下将 token 传递给 WCF 服务,一些像数字这样的值,以便我以后可以在我的服务中使用它。

请您参考如下方法:

使用自定义 header 解决了这个问题。

您可以像这样为您的客户端分配自定义 header :

            IContextChannel contextChannel = (IContextChannel)myServiceProxy; 
            using (OperationContextScope scope = new OperationContextScope(contextChannel)) 
            { 
                MessageHeader header = MessageHeader.CreateHeader("PlayerId", "", _playerId); 
                OperationContext.Current.OutgoingMessageHeaders.Add(header); 
                act(service); 
            } 

在服务端可以得到这个值:

    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; 
        } 
    } 

另见 this question了解如何通过配置文件设置自定义 header 。