Sunday, December 17, 2006

Call web service from C# client using basic authentication

The C# class Credentials is used to put authentication information into the SOAP header, not the HTTP header, which would lead to some problem when calling a java-based web service.
In order to invoke web service protected by basic authentication from a C# client, we must override the GetWebRequest() method.
The solution is as follows:
protected override System.Net.WebRequest GetWebRequest(Uri uri){
System.Net.WebRequest request = base.GetWebRequest (uri);
string username = "Test";
string password = "Test";
string auth = username + ":" + password;
byte[] binaryData = new Byte[auth.Length];
binaryData = Encoding.UTF8.GetBytes(auth);auth = Convert.ToBase64String(binaryData);
auth = "Basic " + auth;
request.Headers["AUTHORIZATION"] = auth;
return request;
}
2 related posts can be found at: thescripts developer network , Clinton Davidson's blog .