我有一些代码调用 HttpWebRequest 的 GetResponse() 方法来从 URL 检索 HTML 并将其返回给调用方法。
这在我的开发和 QA 环境中一直运行良好,但现在我已经将它上传到我的 UAT 服务器,我不断收到以下错误:
远程服务器返回错误:(404) Not Found。
Dev/QA 和 UAT 之间的主要区别是 UAT 使用基于 SSL/HTTPS 的 URL,而 Dev/QA 使用 HTTP。我引入了以下代码行来帮助我进一步进步:
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
其中 AcceptAllCertifications 始终返回 true 但我仍然收到 404 错误。
我之前遇到此错误的人已经能够通过仅确保用于 HttpWebRequest 的 URI 末尾没有斜杠来解决问题(请参阅:Simple HttpWebRequest over SSL (https) gives 404 Not Found under C#)但这没有什么不同对我来说。
我现在已经尝试了这篇文章中的建议(参见:HttpWebResponse returns 404 error),我在页面上呈现了异常。这绕过了黄色警告屏幕并为我提供了更多信息,包括它试图从中获得响应的 URL。但是,当我将 URL 复制并粘贴到我的浏览器中时,它可以正常工作并在页面上呈现 HTML。因此,我很高兴在 GetResponse 调用中使用了正确的 URL。
有没有人知道是什么让我如此悲伤?如前所述,这似乎只是我使用 SSL 的 UAT 服务器上的问题。
这是我的代码来协助:
public static string GetHtmlValues()
{
var webConfigParentUrlValue = new Uri(ConfigurationManager.AppSettings["ParentUrl"]);
var destinationUrl = HttpContext.Current.Request.Url.AbsoluteUri;
var path = "DestinationController" + "/" + "DestinationAction" + "?destinationUrl=" + destinationUrl;
var redirect = new Uri(webConfigParentUrlValue, path).AbsoluteUri;
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
var request = (HttpWebRequest)WebRequest.Create(redirect);
//Ensures that if the user has already signed in to the application,
// their authorisation is carried on through to this new request
AttachAuthorisedCookieIfExists(request);
HttpWebResponse result;
try
{
result = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
result = ex.Response as HttpWebResponse;
}
String responseString;
using (Stream stream = result.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
responseString = reader.ReadToEnd();
}
return responseString;
}
错误在页面上呈现时的更多详细信息:
最佳答案
我遇到了类似的情况,但有不同的错误消息。我的问题原来是我的 UAT 环境是带有 .NET 4.5 的 Windows 2008。在此环境中,SSL 握手/检测的执行方式与大多数 Web 浏览器不同。所以我看到 URL 在 Web 浏览器中没有错误地呈现,但我的应用程序会生成错误。我的错误消息包括“基础连接已关闭:发送时发生意外错误”。这可能是您的问题。
我的解决方案是强制更改协议(protocol)。我检测到特定错误,然后强制更改应用程序的安全协议(protocol)并重试。
这是我使用的代码:
catch (Exception ex)
{
if(ex.Message.Contains("The underlying connection was closed: An unexpected error occurred on a send."))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
// retry the retrieval
}
}
关于c# - HttpWebRequest.GetResponse() 返回 404 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28396989/