【发布时间】:2018-02-02 19:08:40
【问题描述】:
我面临一个问题,即我的 Web API 在本地系统上运行良好,但在部署到服务器上时却产生了问题。我已经检查,交叉检查了多次,看看我是否遗漏了配置中的任何内容,但一切都井井有条。 下面是我正在使用的代码。 抛出此错误的行是: using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
public static string PostDataToWebService(string stream, string CustIP)
{
var _url = AdditionalSetting.AutoEuroURL;
string soapResult = string.Empty;
try
{
XmlDocument soapEnvelopeXml = CreateSoapEnvelope(stream);
HttpWebRequest webRequest = CreateWebRequest(_url, CustIP);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
asyncResult.AsyncWaitHandle.WaitOne();
using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
}
}
catch (WebException wbex)
{
using (var ResStream = wbex.Response.GetResponseStream())
using (var reader = new StreamReader(ResStream))
{
ErrorLog.ErrorLogs("WebException at AutoEurope Call web service : " + reader.ReadToEnd());
}
}
return soapResult;
}
private static XmlDocument CreateSoapEnvelope(string stream)
{
XmlDocument soapEnvelop = new XmlDocument();
try
{
soapEnvelop.LoadXml(stream);
}
catch (Exception ex)
{
}
return soapEnvelop;
}
private static HttpWebRequest CreateWebRequest(string url, string CustIP)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", "OTA");
webRequest.Headers.Add("X-Forwarded-For", "\"" + CustIP + "\"");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
webRequest.KeepAlive = false;
webRequest.ProtocolVersion = HttpVersion.Version10;
return webRequest;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
我得到的 CustIP 是我在我的方法中作为参数得到的请求 IP 地址。它的格式正确。 任何建议都会有所帮助。
【问题讨论】:
-
一些网络错误与防火墙有关。您是否尝试禁用防火墙或至少添加启用规则?
-
您要连接的 URL 是 HTTP 还是 HTTPS URL?如果是 HTTPS,则 TLS 协商期间的问题可能会导致此问题。另外,考虑在
BeginGetResponse()之前记录一条消息,这样您就可以看到Begin和End之间经过了多少时间。如果它正在连接,但您的代码没有响应,则服务器可能正在超时并关闭连接。 -
另外,尝试将异步
Begin()/WaitOne()/End()更改为同步GetResponse()。您正在使用异步方法来获取响应,但无论如何都会阻塞第一个线程。 -
@krs 我无法禁用防火墙并与添加启用规则有关,我该怎么做?
-
@Trevor 我所有的请求都是 HTTPS,这是访问服务所必需的。
标签: c# asp.net-web-api system.net.sockets