【问题标题】:HttpWebRequest to https server works in fiddler but NOT from Visual StudioHttpWebRequest 到 https 服务器在提琴手中工作,但不是来自 Visual Studio
【发布时间】:2023-09-21 08:44:02
【问题描述】:

这里是场景。我编写了代码,使用数字证书从安全 url 获取 cookie,然后使用检索到的 cookie 和相同的数字证书将数据 POST 回另一个 url。 GET 工作并检索 cookie,POST 返回错误 500。我安装了 fiddler 以查看发生了什么...POST 看起来很好...cookies 存在。我在 fiddler 中使用了允许通过拖放创建请求的功能。发布与 Fiddler 中记录的 C# 代码中记录的完全相同的 POST,它可以正常工作!

Fiddler 做了哪些 Visual Studio 没有做的事情?如果 fiddler 可以 POST 数据但 Visual Studio 返回错误 500,它一定是在做某事。下面是代码:

X509Certificate cert = new X509Certificate("mycert.pfx", "certpassword");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://servertoGETcookies/fileUpload.html");
req.CookieContainer = new CookieContainer();
req.Method = "GET";
req.ClientCertificates.Add(cert);

HttpWebResponse Response = (HttpWebResponse)req.GetResponse();
CookieCollection ck = req.CookieContainer.GetCookies(req.RequestUri);
string strcookie = ck[0].Value;
string strcookie2 = ck[1].Value;
Response.Close();

req = (HttpWebRequest)WebRequest.Create("https://servertoPOSTdatawithcookies/main");
req.CookieContainer = new CookieContainer();
Cookie auth = new Cookie("_wl_authcookie_", strcookie2);
Cookie jsess = new Cookie("JSESSIONID", strcookie);
auth.Domain = "server";
jsess.Domain = "server";
req.CookieContainer.Add(auth);
req.CookieContainer.Add(jsess);
req.ClientCertificates.Add(cert);
req.Method = "POST";

Byte[] data = ReadByteArrayFromFile("filewithdatatoPOST.txt");
req.ContentLength = data.Length;
Stream myStream = req.GetRequestStream();
myStream.Write(data, 0, data.Length);
myStream.Close();

HttpWebResponse Response2 = (HttpWebResponse)req.GetResponse();
Stream strm = Response2.GetResponseStream();
StreamReader sr2 = new StreamReader(strm);
Response2.Close();

【问题讨论】:

    标签: c# post httpwebrequest fiddler


    【解决方案1】:

    如果你设置了你的代码是否工作

    req.ServicePoint.Expect100Continue = false; 
    

    在您的所有 WebRequest 上?

    【讨论】:

    • 谢谢,但现在还有另一个问题。来自提琴手的帖子以预期的结果响应(即提交的 x)。来自 Visual Studio 的帖子就像没有帖子一样(即就像我没有发布任何内容一样)。
    • 我发布的文件中的文本假设就像我按下按钮上传带有数据的文件一样:code--timestamp Content-Disposition: form-data; name="action" FILEUPLOAD --timestamp Content-Disposition: form-data; name="browseFile";filename="fileuploading.txt" Content-Type: text/plain Meter Daily *** 12345,123,Unit,04/11/2011 1,123.000 2,123.000
    • 对不起...试图标记为有用,但我在这里没有足够的声誉。
    【解决方案2】:

    解决了!!!它与 Expect100Continue 无关。

    所以经过数周的故障排除......6 个不同的程序员......我想通了。我不确定这是否总是正确的,但在这种情况下,问题在于我们从中获取 cookie 的 url:

    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://servertoGETcookies/fileUpload.html");
    

    与我们将数据发回的网址不同:

    req = (HttpWebRequest)WebRequest.Create("https://servertoPOSTdatawithcookies/main");
    

    获取 cookie 并返回到相同的 url 解决了这个问题:

    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://servertoGETandPOSTcookies/main");
    req = (HttpWebRequest)WebRequest.Create("https://servertoGETandPOSTcookies/main");
    

    【讨论】:

      最近更新 更多