How to add basic authentication header to WebRequest

user4041873 picture user4041873 · Sep 15, 2014 · Viewed 60.4k times · Source

I have a basic WCF service and I want to test it using HttpWebRequest. The problem is that I use basic authentication. How do I add a header with basic authentication?

That's my code so far:

var request = (HttpWebRequest)WebRequest.Create(url);

Thanks

Answer

Dawid O picture Dawid O · Sep 15, 2014

Easy. In order to add a basic authentication to your HttpRequest you do this:

string username = "Your username";
string password = "Your password";

string svcCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(username + ":" + password));

request.Headers.Add("Authorization", "Basic " + svcCredentials);

In basic authentication you need to use Base64 to encode the credentials.