How to add basic authentication header to WebRequest [duplicate]

送分小仙女□ 提交于 2019-11-27 15:46:54

问题


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.



来源:https://stackoverflow.com/questions/25852551/how-to-add-basic-authentication-header-to-webrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!