使用Web引用进行HTTP身份验证
问题描述:
我有一个从WSDL创建的Web参考,但是除非输入用户名/密码,否则不允许调用该函数. XML工具包的原始代码为:
I have a web reference created from the WSDL, but I'm not allowed to call the function unless I pass in the username / password; the original code for the XML toolkit was:
Set client = CreateObject("MSSOAP.SOAPClient30")
URL = "http://" & host & "/_common/webservices/Trend?wsdl"
client.mssoapinit (URL)
client.ConnectorProperty("WinHTTPAuthScheme") = 1
client.ConnectorProperty("AuthUser") = user
client.ConnectorProperty("AuthPassword") = passwd
On Error GoTo err
Dim result1() As String
result1 = client.getTrendData(expression, startDate, endDate,
limitFromStart, maxRecords
如何将AuthUser/AuthPassword添加到新代码中?
How do I add the AuthUser/AuthPassword to my new code?
新代码:
ALCServer.TrendClient tc = new WindowsFormsApplication1.ALCServer.TrendClient();
foreach(string s in tc.getTrendData(textBox2.Text, "5/25/2009", "5/28/2009", false, 500))
textBox1.Text+= s;
答
找到了它:即使Preauthenticate == True,它也不会这样做.您必须重写WebRequest:
Found it: Even if Preauthenticate==True, it doesn't do it. You have to overried the WebRequest:
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;
}
由于它是作为子类创建的,因此可以将存根保存在单独的文件中,并重新构建Reference.cs不会破坏您.
Since it gets created as a partial class, you can keep the stub in a separate file and rebuilding the Reference.cs won't clobber you.