Making a POST request in C# with Basic Authentication

Making a GET request using Basic Authentication is pretty easy using the BCL:

var webRequest = WebRequest.Create(uri);
webRequest.Credentials = new NetworkCredential("userName", "password");
using (var webResponse = webRequest.GetResponse())
{
    using (var responseStream = webResponse.GetResponseStream())
    {
        return new StreamReader(responseStream).ReadToEnd();
    }
}

As is making an unauthenticated POST request:

var webRequest = WebRequest.Create(uri);
webRequest.Method = "POST";
var bytes = Encoding.UTF8.GetBytes(data);
webRequest.ContentLength = bytes.Length;
webRequest.ContentType = "application/x-www-form-urlencoded";
using (var requestStream = webRequest.GetRequestStream())
{
	requestStream.Write(bytes, 0, bytes.Length);
}
...

But, for some reason, combining the two resulted in me being redirected to the login page. I thought it might need to be done in a specific order (like setting the content length before the type), but nothing I tried made any difference.

Luckily a StackOverflow post suggested an alternative, explicitly setting the Authorization header:

var webRequest = WebRequest.Create(uri);
webRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));
webRequest.Method = "POST";
...

Which works as expected.

Leave a comment