使用Web引用进行HTTP身份验证

时间:2009-05-28 20:35:00

标签: authentication soap-client

我有一个从WSDL创建的Web引用,但除非我传入用户名/密码,否则我不允许调用该函数; XML工具包的原始代码是:

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添加到我的新代码中?

新代码:

    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;

1 个答案:

答案 0 :(得分:1)

找到它:即使Preauthenticate == True,它也不会这样做。你必须重写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不会破坏您。