使用 Web 应用程序调用服务时出现“无法连接到远程服务器”错误。但是当我从控制台应用程序中使用它时,会运行相同的代码。这是堆栈跟踪:-
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)
这是我正在使用的代码:-
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();
}
web.config 中是否有任何设置需要我提到才能在 Web 应用程序中工作?