1

Within my WebApi controller, I am trying to call an .asmx SOAP Service.

I used VS2015 to generate the SoapClient proxy as a Service Reference.

My main problem is that I need to set the Authorization header to contain a Bearer token.

I thought I had a solution, using @SimonRC's answer here. My code looks like this:

using (OperationContextScope scope = new OperationContextScope(_client.InnerChannel))
{
    var httpRequestProperty = new HttpRequestMessageProperty();
    httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] = "Bearer blahblahblah";
    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;

    string packetData = await _client.GetPacketAsync(packetNumber, packetDate.ToString("ddMMMyy"));

    response = new Packet()
    {
        packet = packetData
    };
    return response;
}

This works great when I debug in VS2015, but when I deploy my WebApi to Azure I'm getting this error:

The value of OperationContext.Current is not the OperationContext value installed by this OperationContextScope.

I'm looking for either (a) an solution to resolve this error, or (b) an alternate way to set the Authorization header to contain a Bearer token.

Mike Taverne
  • 9,156
  • 2
  • 42
  • 58
  • Great textbook example of using OperationContext, the context that you can pass along using WCF is one of the best all around reasons to use it. You can do some really cool stuff with tokens and identifiers always being available. – Chris Marisic Jun 02 '17 at 19:09

1 Answers1

2

Changing the call to the SOAP service to be synchronous instead of async solved the problem.

Basically, I changed this:

string packetData = await _client.GetPacketAsync(packetNumber, packetDate.ToString("ddMMMyy"));

To this:

string packetData = _client.GetPacketAsync(packetNumber, packetDate.ToString("ddMMMyy"));

And of course corresponding changes up the chain to remove async Task everywhere. That did it.

I got the idea to remove async from @ChrisMarisic's comment here that "I know this question is old, but there is pretty much no reason to use async inside a WCF service ever." So glad for comments like these!

Mike Taverne
  • 9,156
  • 2
  • 42
  • 58