Reputation: 152
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 :(
Upvotes: 0
Views: 582
Reputation: 1
I had same problem and resolved with setting proxy of httpwebrequest as below.
httpRequest.Proxy = new WebProxy(hostname, portno);
Upvotes: 0
Reputation: 448
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; };
Upvotes: 1
Reputation: 152
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.
Upvotes: 1