-->

How to add basic authentication header to WebReque

2019-01-23 11:27发布

问题:

This question already has an answer here:

  • HttpWebRequest using Basic authentication 8 answers

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

回答1:

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.