通过身份验证 Header API WCF Soap C# .Net

Pass Authentication Header API WCF Soap C# .Net

我正在尝试使用 WCF 向 soap 中的 API 发送请求,在 API 文档中我被告知首先我需要通过以下包含固定令牌的身份验证 header:

<soapenv:Header>
<Token xmlns="Token">12345as566788ds900987654</Token>
</soapenv:Header>

通过并验证此令牌后,我访问 class 我需要发送文件,我尝试使用下面的代码来 assemble 搜索,但我收到错误: System.ServiceModel.FaultException: 通知我需要在header.中传递token标签 下面是我的尝试方式:

using (new OperationContextScope(client.InnerChannel))
{
   HttpRequestMessageProperty requestMessage = new();
   requestMessage.Headers["Token"] = "12345as566788ds900987654";

   var result= client.uploadFile(file);
}

您可以在客户端试试这个:

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