0

I know that I can add headers to a WebService proxy class that extends SoapHttpClientProtocol by overriding GetWebRequest. This is working ok. My problem is that I am passing in the bearer token value that I need to add to the header when I instantiate my webservice class; however it's not being used, and I cannot figure out what I'm doing wrong.

public partial class MyService : System.Web.Services.Protocols.SoapHttpClientProtocol {
        
private string _token;
    
private void SetToken(string t) { this._token = t; }
private string GetToken() { return this._token; }
    
protected override System.Net.WebRequest GetWebRequest(Uri uri) {
     System.Net.WebRequest request = base.GetWebRequest(uri);
     request.Headers.Add("Authorization", GetToken());
    
     System.IO.File.WriteAllText(@"C:\temp\test.txt", request.Headers.ToString());
     return request;
     }
    
public MyService (string t){
     SetToken(t);
     // ... other stuff
     }
}

From my codebehind, I instantiate MyService and pass the constructor the token.

However, when I dump the headers to a text file before I return the request, the output looks like this:

User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.42000)
Authorization:

So I know that the override is being called and that the header is being added, it's simply not picking up the value of the bearer token from the variable, _token, that should be set when the class is instantiated.

What am I missing?

Chris M
  • 3
  • 1

1 Answers1

0

Try to use this syntax for adding token:


request.PreAuthenticate = true;
request.Headers.Add("Authorization", "Bearer " + GetToken());


Serge
  • 40,935
  • 4
  • 18
  • 45
  • No dice. Same outcome. It's adding the header, but I can't manage to get the token value into it. – Chris M Jan 30 '21 at 14:25
  • Are you sure that _token is not empty? – Serge Jan 30 '21 at 15:10
  • Did you try System.IO.File.WriteAllText(@"C:\temp\test2.txt", _token); – Serge Jan 30 '21 at 15:38
  • Yah. Tried all of that. SetToken("foo"); in the constructor produces the same output ... No value written to the header. – Chris M Jan 30 '21 at 17:31
  • But maybe request.Headers.ToString() doesn' show all headers. Did you try to send the request. Is it working with APIs or giving 401 Error? – Serge Jan 30 '21 at 17:52
  • I think you're right. Seems like Headers.ToString() doesn't print the value.. SMH. My request still fails, but I can see that the header has the authorization token when the request is made over the wire (via wireshark). At least now I know this was a red herring and I can move on to try and diagnose the real problem.. Thanks for the help. Much appreciated. – Chris M Jan 30 '21 at 22:02