调用API接口:
首先需要 CredentialCache 对象,然后设置NetworkCredential 的用户名密码和Basic;最后需要在request的Headers中加上Authorization节点,此节点是由basic和用户名+密码的ASCIIEncoding类型的二进制字符串组成的。request的PreAuthenticate属性必须设置成true。
CredentialCache cache = new CredentialCache();
NetworkCredential nc = new NetworkCredential(userName, password);
cache.Add(new Uri(url), "Basic", nc);
request.PreAuthenticate = true;
request.Credentials = cache;
request.Headers.Add("Authorization",
"Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes($"{userName}:{password}")));
调用SOAP接口:
设置了NetworkCredential对象的用户名和密码
service.Credentials = new NetworkCredential(securelyStoredUserName, securelyStoredPassword);
我在项目中只设置了NetworkCredential就验证成功了,所以就没有用下面的方式,如果有验证不成功,除了用户名密码不正确,可以采用下面的方式。
1.在初始化SOAP类时,需要先将NetworkCredential赋值
service.Credentials = new NetworkCredential(securelyStoredUserName, securelyStoredPassword);
2.需要在根据wsdl生成的类中添加拦截request请求 直接在headers中添加上Authorization节点
protected override WebRequest GetWebRequest()
{
Uri u = new Uri(Url + "?wsdl");//由于当时没有用到此方法 不清楚获取uri时 需不需要加上?wsdl,用到的自己测试。
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(u);
if (PreAuthenticate)//使用时,必须设置服务类的PreAuthenticate属性为true并设置Credentials属性
{
NetworkCredential networkcredential = base.Credentials.GetCredential(uri, "Basic");
if (networkcredential != null)
{
request.Headers.Add("Authorization",
"Basic " + Convert.ToBase64String(new UTF8Encoding().GetBytes($"{networkcredential.UserName}:{networkcredential.Password}")));
}
else
throw new ApplicationException("No network credentials");
}
return request;
}