This question already has an answer here:
这个问题已经有了答案:
- HttpWebRequest using Basic authentication 7 answers
- 使用基本身份验证7回答HttpWebRequest
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?
我有一个基本的WCF服务,我想使用HttpWebRequest来测试它。问题是我使用基本的身份验证。如何添加具有基本身份验证的头?
That's my code so far:
到目前为止,这是我的代码:
var request = (HttpWebRequest)WebRequest.Create(url);
Thanks
谢谢
1 个解决方案
#1
50
Easy. In order to add a basic authentication to your HttpRequest you do this:
一件容易的事。为了向HttpRequest添加基本身份验证,您可以这样做:
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.
在基本身份验证中,您需要使用Base64来对凭证进行编码。
#1
50
Easy. In order to add a basic authentication to your HttpRequest you do this:
一件容易的事。为了向HttpRequest添加基本身份验证,您可以这样做:
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.
在基本身份验证中,您需要使用Base64来对凭证进行编码。