Getting The remote server returned an error: (504) Gateway Timeout for WebAPI

Getting The remote server returned an error: (504) Gateway Timeout for WebAPI

我正在使用以下代码通过 WebRequest 从我的 C# 代码进行 API 调用:

public object GetData() 
{
 object response = "";
 string token = "EF232354";
 string baseUrl = ConfigurationManager.AppSettings["BaseURL"].ToString();
 string endPoint = ConfigurationManager.AppSettings["EndPoint"].ToString();

 var httpWebRequest = (HttpWebRequest) WebRequest.Create(baseUrl + endPoint);

 httpWebRequest.ContentType = "application/json";
 httpWebRequest.Method = HttpVerb.GET.ToString();
 httpWebRequest.Headers.Add("token", token);

 var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();
 Stream dataStream = httpResponse.GetResponseStream();
 StreamReader reader = new StreamReader(dataStream);

 using(JsonReader sdr = new JsonTextReader(reader)) 
 {
  JsonSerializer serializer = new JsonSerializer();
  response = serializer.Deserialize(sdr);
 }
  return response;
}

有时我得到:

Message: The remote server returned an error: (504) Gateway Timeout.

Exception Type: System.Net.WebException

WebRequest 一次可以发出多少个请求?

当我注意到没有处理响应时,我正在调整问题以演示读取内存流。这有 95% 的可能性是您的潜在问题。 Streams 和 StreamReader 也是一次性的,应该用 using() 闭包包装。

public object GetData() 
{
  object response = "";
  string token = "EF232354";
  string baseUrl = ConfigurationManager.AppSettings["BaseURL"].ToString();
  string endPoint = ConfigurationManager.AppSettings["EndPoint"].ToString();

  var httpWebRequest = (HttpWebRequest) WebRequest.Create(baseUrl + endPoint);

  httpWebRequest.ContentType = "application/json";
  httpWebRequest.Method = HttpVerb.GET.ToString();
  httpWebRequest.Headers.Add("token", token);

  using (var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse())
  {
    using (Stream dataStream = httpResponse.GetResponseStream())
    {
      using (StreamReader reader = new StreamReader(dataStream))
      {
        using(JsonReader sdr = new JsonTextReader(reader)) 
        {
          JsonSerializer serializer = new JsonSerializer();
          response = serializer.Deserialize(sdr);
        }
        return response;
      }
    }
    httpResponse.Close(); // For good measure. *should* be covered by Dispose.
  }
}