C#:在进行SOAP调用时如何使用HTTP身份验证?

C#:在进行SOAP调用时如何使用HTTP身份验证?,c#,visual-studio-2010,web-services,soap,http-headers,C#,Visual Studio 2010,Web Services,Soap,Http Headers,因此,我尝试对使用HTTP身份验证的Web服务进行SOAP调用。我在VisualStudio中添加了一个web引用,它为我生成了一个包装器类。下面是我如何拨打电话的示例代码: var prox = new WebserviceNamespace.WebService(); prox.Credentials = new NetworkCredential("username", "password"); prox.PreAuthenticate = true; var resp = pro

因此,我尝试对使用HTTP身份验证的Web服务进行SOAP调用。我在VisualStudio中添加了一个web引用,它为我生成了一个包装器类。下面是我如何拨打电话的示例代码:

 var prox = new WebserviceNamespace.WebService();
 prox.Credentials = new NetworkCredential("username", "password");
 prox.PreAuthenticate = true;
 var resp = prox.webMethod(null, null);
最后一行抛出“身份验证失败”消息

我使用wireshark检查它是否试图将基本身份验证添加到HTTP数据包中,但看起来不是这样。以下是wireshark的输出:

 POST /cms/services/WebService HTTP/1.1\r\n
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.34209)\r\n
VsDebuggerCausalityData: uIDPo7e/OYIGV2VDs7nYMO5QmegAAAAAWxFxk5NzcUSF5zGIxQ1REwb488ITippOiEKaDSmuFDkACQAA\r\n
Content-Type: text/xml; charset=utf-8\r\n
SOAPAction: ""\r\n
Host: sub.domain.com\r\n
Content-Length: 343\r\n
Expect: 100-continue\r\n
Connection: Keep-Alive\r\n
\r\n
[Full request URI: http://sub.domain.com/cms/services/WebService3.0]
[HTTP request 2/2]
[Response in frame: 265321]eXtensible Markup Language
<?xml
<soap:Envelope
    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <webMethod
            xmlns="WebService">
            <in0 xsi:nil="true"/>
            <in1
                xsi:nil="true"/>
            </webMethod>
        </soap:Body>
    </soap:Envelope>

有人知道我做错了什么吗?

终于明白了。这篇很小的文章为我提供了关键:

基本上,只有当服务器质疑您的请求时,才会使用Credentials属性。如果服务器不挑战它,它可能会失败(就像发生在我身上的那样)。我要做的是编辑自动生成的代理类,并将此代码添加到其中(受上面链接的启发):


有了它,我就不会再收到身份验证错误了

你这个小开膛手!非常感谢您发布这篇文章,经过数小时的努力,我的请求得以实现,添加了几行代码(当然还输入了我自己的用户名和密码),一切顺利!谢谢,谢谢,谢谢!:-)
Authorization: Basic SUNOOnNwc3pK
protected override WebRequest GetWebRequest(Uri uri)
    {
        HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(uri);
        String authInfo = Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
        request.Headers["Authorization"] = "Basic " + authInfo;
        return request;
    }