简体   繁体   中英

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

When I run the code below from a console app it works perfectly.

        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();
        }

However when I run the same code from ASP.NET I get:

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

Any ideas, please.

Update: The remote end is not seeing the data we send through ASP.NET so the problem is definitely on the sending side.
Update 2 : Some sites, suggest impersonation, that didn't work :(

Having not found a better solution and having code release deadline I am just going to call a Console app from the ASP.NET code. Solution is below

    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;

I realize that this is not an ideal solution and will delete/modify this answer if someone suggests a better approach.

I use HttpWebRequest in an ASP.NET application and works just fine.

Based on the error you see in Fiddler I would say it is a problem with the HTTPS certificate validation or the default security protocol. Probably a different default policy applies when you run the code in a console application and that is why it works there. Try to add these lines below the 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM