I am getting "Unable to connect to a remote server" error while calling a service using Web Application. But the same code runs when I call it from a console application. I just have the URL of the service.
Here is the stack trace:
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot,
SocketAddress socketAddress)
at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure,
Socket s4, Socket s6, Socket& socket, IPAddress& address,
ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout,
Exception& exception)
Here is the code which I am using:
HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
X509Certificate cert = X509Certificate.CreateFromCertFile(certificatePath);
req.ClientCertificates.Add(cert);
using (StreamReader sr = File.OpenText(inFilePath))
{
string xml = sr.ReadToEnd();
string postRaw = string.Format("request={0}", System.Web.HttpUtility.UrlEncode(xml));
byte[] buf = Encoding.UTF8.GetBytes(postRaw);
req.ContentLength = buf.Length;
try
{
Stream s = req.GetRequestStream(); //This is where I get the error.
s.Write(buf, 0, buf.Length);
s.Close();
}
catch (Exception ex)
{
}
}
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
if (resp.StatusCode == HttpStatusCode.OK)
{
StringBuilder sb = new StringBuilder();
using (StreamReader reader = new StreamReader(resp.GetResponseStream(), System.Text.Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
sb.Append(line + "\r\n");
}
}
string resXml = sb.ToString();
}
Is there any setting in web.config or on IIS which I need to mention for this to work in a web application?
One of my team member has already asked this question but no one has replied to it as yet. So that's why I'm posting it again.
This is the exact inner exception:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond XX.XX.XXX.XXX:443
Ok! So your Url is SSL.
We have 2 possibilities:
If you test web application in a same computer as the console application runs, change the identity of your application pool. VS uses an identity and IIS uses the diffrent one.
If not check your web.config file for settings to bypass firewall
<system.net>
<defaultProxy>
<proxy usesystemdefault="true" proxyaddress="http://proxy:port" bypassonlocal="false" />
</defaultProxy>
</system.net>