Adding Authorization Header to Web Reference

别来无恙 提交于 2019-12-04 10:22:07

问题


I'm attempting to make requests to a client's web service (I don't know the underlying platform at the client). I've consumed the client's WSDL in Visual Studio 2010 using "Add Web Reference" and generated my proxy class (called "ContactService").

I now need to add an authorization header like the one below to my service request.

Header=Authorization & Value=Basic 12345678901234567890

(the "123456..." value above is just placeholder)

ContactService service = new ContactService();

//not sure if this is the right way - it's not working
WebClient client = new WebClient();
client.Headers.Add("Authorization", "Basic 12345678901234567890");            
service.Credentials = client.Credentials;

int contactKey = null;
try
{                
   contactKey = service.CreateContact("ABC", emailAddress, firstName, lastName, null);
}

What is the proper way of adding the authorization header to the service request?

Thank you!


回答1:


The above response was on the right track, but it just had to be in a different location.

I added this to my web reference proxy class that .Net generated:

protected override WebRequest GetWebRequest(Uri uri)
    {
        HttpWebRequest req = (HttpWebRequest)base.GetWebRequest(uri);            
        req.Headers.Add(HttpRequestHeader.Authorization,
                "Basic " + "12345678901234567890");

        return req;
    }

A Web Reference proxy class extends System.Web.Services.Protocols.SoapHttpClientProtocol. This class contains a call to System.Net.WebRequest.GetWebRequest(Uri uri). A WebRequest allow us to set specific headers on the request when the proxy class' methods are invoked.

Thanks for your help!




回答2:


There are a couple of changes to make.

Firstly, there is a handy constant HttpRequestHeader.Authorization.

Secondly, are they expecting the header to be Base64 Encoded - this is normally required for basic authentication.

WebClient.Headers.Add(HttpRequestHeader.Authorization, 
    "Basic " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("12345678901234567890")));



回答3:


I am writing this for whom that has this problem now. As in preceding answers mentioned inheritance hierarchy goes up to WebClientProtocol class, this class has a ICredentials property, simply set this property by a NetworkCredential instance as below:

YourServis.Credentials = new NetworkCredential("UserName", "Password", "Domain");

I think taht is simplest way without changing Reference.cs or adding headers.



来源:https://stackoverflow.com/questions/14488991/adding-authorization-header-to-web-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!