Sunday, 3 May 2015

C# - WebClient Authentication not working

Today I had a scenario where I was using WebClient class to POST XML to a particular Url.

Even after many trials, the authentication was not working fine.

Finally I had to do it the old fashion way of specifying the authorization credentials in the header.

This scenario happens because WebClient doesn't send the Authorization header untill it receives a 401 status.

The code that failed:

string xml = @"<messages>......</messages> ;
string url = new UriBuilder("http", "www.abc.com", 9443).ToString();

// create a client object
using (System.Net.WebClient client = new System.Net.WebClient())
{
client.Credentials = new NetworkCredential("user1", "password1");
// performs an HTTP POST
string resp = client.UploadString(url, xml);
txtResponse.Text = "Response:" + resp;
}


The workaround:

string xml = @"<messages>......</messages> ;
string url = new UriBuilder("http", "www.abc.com", 9443).ToString();

// create a client object
using (System.Net.WebClient client = new System.Net.WebClient())
{
client.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("user1:password1"));
// performs an HTTP POST
string resp = client.UploadString(url, xml);
txtResponse.Text = "Response:" + resp;
}

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete