首页 > 解决方案 > HttpWebRequest 适用于 windows 窗体但不适用于 Web API

问题描述

我需要从 WEB API 方法调用 HTTPS POST 服务。我正在使用 HttpWebRequest 调用此 API,但是我收到错误消息“连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立连接失败,因为连接的主机未能响应 xxxx:443”

当我尝试在 Windows 窗体中调用此 API 时,它运行良好。

HttpWebRequest r = null; 
HttpWebResponse rsp = null; 
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; 
r = (HttpWebRequest)System.Net.WebRequest.Create("url"); 
String d = "Serialize JSON" 
r.Method = "POST"; 
r.ContentType = "application/json"; 
StreamWriter wr = new StreamWriter(r.GetRequestStream()); 
wr.WriteLine(d); 
wr.Close(); 
rsp = (HttpWebResponse)r.GetResponse();
StreamReader reader = new StreamReader(rsp.GetResponseStream()); 
String dd = reader.ReadToEnd();

标签: c#asp.net-web-api

解决方案


可能是因为您正在尝试使用 SSL,从最后一部分 - xxxx:443。我的理解是 443 用于 SSL。如果我不正确,很高兴有人纠正我。

看看以下内容,这可能会对您有所帮助:

https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/working-with-ssl-in-web-api


推荐阅读