0

我在尝试使用 Digest 身份验证与 Web 服务器 (Apache 2.2.17) 通信并使用 POST 方法发送数据时遇到问题:它总是返回 401 错误。但是,当我们不发布数据或 Fiddler 正在运行时(即使在发布数据时),它也能正常工作......您知道什么会导致问题吗?

public void DoRequest(string v_strURL, XmlDocument v_objXMLDoc)
{

var credentialCache = new CredentialCache();

credentialCache.Add(new Uri("http://" + ServerIP + "/"), "Digest", new NetworkCredential("admin", "test", "realm"));

String RequestContent = "request=" + v_objXMLDoc.InnerXml.Replace(' ', '+');
Uri Url = new Uri(v_strURL);

HttpWebRequest objHttpWebRequest;
HttpWebResponse objHttpWebResponse = null;

Stream objRequestStream = null;

byte[] bytes = new byte[0];
bytes = System.Text.Encoding.UTF8.GetBytes(RequestContent);

objHttpWebRequest = (HttpWebRequest)WebRequest.Create(v_strURL);
objHttpWebRequest.UserAgent = "MySampleCode";
objHttpWebRequest.Credentials = credentialCache;
objHttpWebRequest.Method = "POST";
objHttpWebRequest.ContentLength = bytes.Length;
objHttpWebRequest.ContentType = "text/xml; encoding='utf-8'";
objHttpWebRequest.ContentType = "application/x-www-form-urlencoded";

objRequestStream = objHttpWebRequest.GetRequestStream();
objRequestStream.Write(bytes, 0, bytes.Length);
objRequestStream.Close();

objHttpWebResponse = (HttpWebResponse)objHttpWebRequest.GetResponse();

}
4

3 回答 3

2

是否有某些原因您要设置 Content-Type 标头两次?这不太可能做你想做的事。另外,为什么将凭据与服务器 IP 而不是主机名一起放在缓存中?

HTTP/401 表明服务器正在向客户端挑战凭据。客户端应通过重新提交附加凭据的请求来响应。一个关键问题是,在失败的情况下是客户端尝试发送凭据但被拒绝,还是根本不尝试发送凭据?

如果 Fiddler “神奇地”为您解决问题,您可能应该使用 Netmon 或 Wireshark 进行较低级别的查看。

于 2011-09-05T16:31:39.620 回答
1

HttpWebRequest.Create() 调用中的主机名(即 v_strUrl)与 credentialCache.Add() 调用中的主机名(即 ServerIP)是否相同?如果没有,那么这将永远失败。

无需使用 CredentialCache,只需将凭据直接添加到 HttpWebRequest 对象

request.Credentials = new NetworkCredential("user", "password", "realm");

看看这是否有效。

于 2011-09-05T19:31:04.307 回答
0

我们终于解决了这个问题:

objHttpWebRequest.ServicePoint.Expect100Continue = false;
于 2011-09-14T09:20:14.270 回答