Search code examples
c#asp.nethttpwebrequesthttpwebresponse

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 :(


Solution

  • 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.