简体   繁体   中英

C# Passing bearer token to generated proxy class to add header

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?

Try to use this syntax for adding token:


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


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM