Home > Blockchain >  Pass Authentication Header API WCF Soap C# .Net
Pass Authentication Header API WCF Soap C# .Net

Time:09-17

I'm trying to send a request to an API in soap using WCF, in the API documentation I was told that first I need to pass the following authentication header containing a fixed token:

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

After passing and validating this token I access the class I need to send the file, I tried with the code below that I managed to assemble searching, but I'm getting the error: System.ServiceModel.FaultException: informing that I need to pass the token tag in the header. Below how I'm trying to do it:

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

   var result= client.uploadFile(file);
}

CodePudding user response:

You can try this for the client-side:

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

And you can try this on the server-side:

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