HTTP Authentication with Web References

旧城冷巷雨未停 提交于 2019-12-24 08:29:05

问题


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

How do I add the AuthUser/AuthPassword to my new code?

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;

回答1:


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;
    }

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.



来源:https://stackoverflow.com/questions/923015/http-authentication-with-web-references

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