我有一个web服务,它有一个返回值的方法。我的要求是,我想在每个Web请求的头中传递身份验证值,我使用下面给出的代码执行相同的操作
req = WebRequest.Create(http://localhost/test/test.asmx);
string _auth = string.Format("{0}:{1}", "username", "password");
string _enc = Convert.ToBase64String(Encoding.ASCII.GetBytes(_auth));
string _cred = string.Format("{0} {1}", "Basic", _enc);
req.Headers[HttpRequestHeader.Authorization] = _cred;
WebResponse response = (WebResponse)req.GetResponse();
但通过这种方式,我无法调用web方法。有没有办法实现同样的目标。
此外,我尝试在ICredentials的帮助下使用以下给定代码发送身份验证值,但我需要标题值,如“授权:基本YWRtaW46YWRtaW4 =”
ICredentials creds;
creds = new
NetworkCredential("username", "password", "domain");
proxy.Credentials = creds;
string str=proxy.helloworld();
如果有任何方法可以实现这一点,请告诉我。非常感谢。
谢谢
答案 0 :(得分:1)
从this post复制。
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
HttpWebRequest request;
request = (HttpWebRequest)base.GetWebRequest(uri);
if (PreAuthenticate)
{
NetworkCredential networkCredentials =
Credentials.GetCredential(uri, “Basic”);
if (networkCredentials != null)
{
byte[] credentialBuffer = new UTF8Encoding().GetBytes(
networkCredentials.UserName + “:” +
networkCredentials.Password);
request.Headers["Authorization"] =
“Basic” + Convert.ToBase64String(credentialBuffer);
}
else
{
throw new ApplicationException(“No network credentials”);
}
}
return request;
}