0

我正在尝试从 Azure 函数 APP 方法获取数据(此 Get API URL 在直接在浏览器中输入时返回数据),但是当我尝试在我的 C# 代码中调用此 URL 时失败,并出现以下内部异常:

InnerException {“无法从传输连接读取数据:现有连接被远程主机强行关闭。”} System.Exception {System.IO.IOException}

以下是代码:

string html = string.Empty;
        string url = @"https://mgyapi.azurewebsites.net/api/my_get/";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url+ "421?code=xxxxxxxxxxwBuTCJpOIVmqBS8DIgE4MhTA==");
        request.AutomaticDecompression = DecompressionMethods.GZip;
        request.Method = "GET";
        //request.ContentType = contentType;
        request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36";
        request.CookieContainer = new CookieContainer();
        //request.ContentLength = formData.Length;
        request.Accept = "*/*";
        request.Host = "mgyapi.azurewebsites.net";
        request.KeepAlive = true;
        request.Timeout = 999999999;
        // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; 

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) //<----Here exception raises
        using (Stream stream = response.GetResponseStream())
        using (StreamReader reader = new StreamReader(stream))
        {
            html = reader.ReadToEnd();
        }

以下是我在浏览器中看到的请求标头:

Accept: text / html,application / xhtml + xml,application / xml; q = 0.9,image / webp,image / apng,*/*;q=0.8,application/signed-exchange;v=b3
    Accept-Encoding: gzip, deflate, br
    Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
    Cache-Control: max-age=0
    Connection: keep-alive
    Host: mgyapi-v1.azurewebsites.net
    Sec-Fetch-Mode: navigate
    Sec-Fetch-Site: none
    Sec-Fetch-User: ?1
    Upgrade-Insecure-Requests: 1
    User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36
4

1 回答 1

0

在 ASP.Net 中有三个这样的方法用于 webrequest。

  1. HttpWebRequest
  2. 网络请求
  3. HttpRequest

我没有指出上述项目的区别。您可以从这里找到它: ASP.Net 中 HttpWebRequest 和 WebRequest 之间的区别

HttpWebRequest替换为WebRequest并将所有HttpWebResponse替换为WebResponse并查看您得到的输出。我认为这应该可以解决您的问题。

于 2019-10-18T15:02:48.380 回答