【发布时间】:2018-08-04 19:07:03
【问题描述】:
我正在尝试修补一个 .net Web 应用程序,该应用程序经过多年的工作后开始无法获得 UPS 运输报价,这极大地影响了 Web 业务。经过反复试验,我发现以下代码在控制台应用程序中运行良好:
static string FindUPSPlease()
{
string post_data = "<xml data string>";
string uri = "https://onlinetools.ups.com/ups.app/xml/Rate";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
byte[] postBytes = Encoding.ASCII.GetBytes(post_data);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
// get response and send to console
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(new StreamReader(response.GetResponseStream()).ReadToEnd());
Console.WriteLine(response.StatusCode);
return "done";
}
这在 Visual Studio 中运行得很好,并且从 UPS 得到了一个很好的小响应,即 XML 格式当然是错误的。
但是,如果我将此函数粘贴到 Web 应用程序中而不更改单个字符,则会在 request.GetRequestStream() 上引发异常:
身份验证失败,因为远程方已关闭传输流。
我在应用程序的几个不同位置进行了尝试,结果相同。
Web 应用程序环境的哪些方面会影响请求?
【问题讨论】:
-
这有点猜测,但既然你说它在 VS 中有效,但在 web 中无效,这可能是 CORS (developer.mozilla.org/en-US/docs/Web/HTTP/CORS) 问题。较新的浏览器内置了保护措施,以阻止网站不恰当地访问来自其他域的 API 响应。如果您使用的是 Chrome 或 Firefox,您可以获得一个 No-CORS 插件,看看它是否有效?
-
它在 VS 控制台应用程序中有效,但在运行 Web 应用程序时不能在 VS 中。 (顺便说一句,它在网络上也不起作用)。
-
我刚刚发现这篇文章解决了几乎相同的问题,除了它涉及 Web 服务请求。但是,我无法评论那里的评论是否解决了问题。是 TLS 问题吗? stackoverflow.com/questions/48329844/…
标签: c# .net http xmlhttprequest ups