WebRequest System.Net.WebException:无法连接到远程服务器的端口号发生了异常更改

时间:2018-09-08 09:31:47

标签: c# .net self-host-webapi

我有两个使用 System.Web.Http.SelfHost 作为.Net Framework 4.0的自托管.Net应用程序,两个应用程序均通过https进行通信。

第一个应用程序使用端口:3287,第二个应用程序使用端口:3286

当我使用 HttpWebRequest 类从第一个应用程序调用第二个应用程序时,出现此异常

System.Net.WebException: Unable to connect to the remote server ---> 
System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:49543
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()

这是我的C#代码

HttpWebRequest request = WebRequest.Create("https://localhost.company.com:3286/"+ EndPoint) as HttpWebRequest;
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => 
{
    return true;
};
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = data.Length;
request.AllowAutoRedirect = false;
request.Expect = "application/json";
request.GetRequestStream().Write(data, 0, data.Length);
HttpWebResponse httpResponse = request.GetResponse() as HttpWebResponse;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    string s = streamReader.ReadToEnd();
    return s;
}

我正在呼叫端口3286,但在例外情况下,日志端口号已更改为49543。

如果我通过邮递员调用我的应用程序,则可以从中获得响应。

证书localhost.company.com映射到127.0.0.1,我也已映射到主机文件中。

0 个答案:

没有答案