HttpWebRequest/HttpWebResponse 仅适用于控制台应用,不适用于 ASP.NET

HttpWebRequest/HttpWebResponse only works from Console app not ASP.NET

当我从控制台应用程序 运行 下面的代码时,它工作得很好。

        Uri prereqUri = new Uri(PREREQ_URL);
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(prereqUri);

        request.PreAuthenticate = true;
        request.Headers.Add(HttpRequestHeader.Authorization, authorization);
        request.Method = "POST";
        request.KeepAlive = true;

        string responseString = "";
        using (var response = (HttpWebResponse)request.GetResponse())
        {
            responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
        }

然而,当我 运行 来自 ASP.NET 的相同代码时,我得到:

"System.IO.IOException Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."
在 var response = (HttpWebResponse)request.GetResponse()

任何想法,请。

更新:远端没有看到我们通过ASP.NET发送的数据,所以问题肯定在发送端。
更新 2 : 一些网站,建议模仿,但没有用 :(

由于没有找到更好的解决方案并且有代码发布截止日期,我只想从 ASP.NET 代码调用控制台应用程序。解决方案如下

    ProcessStartInfo startInfo = new ProcessStartInfo
    {
        FileName = @"C:\Debug\ConsoleApp.exe",
        UseShellExecute = false,
        RedirectStandardOutput = true,

        Arguments = PREREQ_URL + " " + basicUserName
    };
    if (basicPassword.Length > 0) startInfo.Arguments += " " + basicPassword;

    string responseString = Process.Start(startInfo).StandardOutput.ReadLine();
    return responseString;

我知道这不是一个理想的解决方案,如果有人提出更好的方法,我会delete/modify回答这个问题。

我在 ASP.NET 应用程序中使用 HttpWebRequest 并且工作正常。

根据您在 Fiddler 中看到的错误,我认为这是 HTTPS 证书验证或默认安全协议的问题。当您 运行 控制台应用程序中的代码时,可能会应用不同的默认策略,这就是它在那里工作的原因。 尝试在 WebRequest.Create(..)

下面添加这些行
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

    // Skip validation of remote server's SSL/TLS certificate
    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

我有同样的问题,并通过如下设置 httpwebrequest 代理解决。

httpRequest.Proxy = new WebProxy(hostname, portno);