1
votes

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 use it from a console application. 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;

        Console.WriteLine(string.Format("HTTP status code: {0}, content length: {1}, content encoding: {2}",
            resp.StatusCode, resp.ContentLength, resp.ContentEncoding));

        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 which I need to mention for this to work in a web application?

any help quickly will be much appreciated!! Thanks! - Vinyas Singh