编程语言
首页 > 编程语言> > C#HttpClient-我可以强制关闭连接吗?

C#HttpClient-我可以强制关闭连接吗?

作者:互联网

我们看到一个问题,即客户点击我们的API并在请求完成之前取消了该请求.我们相信他们也正在关闭连接,因此请求不会被写入IIS日志.我正在尝试创建一个跑步者来复制此行为.我不知道如何强制关闭连接,以使服务器无法将数据发送回去?

这是我当前的代码:

 private static async Task RunMe()
    {

        var cts = new CancellationTokenSource();
        cts.CancelAfter(5000);

        using (var client = new HttpClient())
        {
            try
            {
                client.DefaultRequestHeaders.ConnectionClose = true;
                client.DefaultRequestHeaders.Add("x-apikey", "some key");
                Console.WriteLine("making request");
                using (var response = await client.GetAsync("https://foo.com/api/apitest/testcancel", cts.Token))
                {
                    var result = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"Request completed: {result}");
                }
            }
            finally
            {                    
                client.CancelPendingRequests();
                Console.WriteLine("about to dispose the client");
                client.Dispose();
            }
        }
    }
}

该代码在5秒钟后正确取消了该请求,但是IIS在API调用完成(设置为10秒钟)后似乎仍会发送回数据.

如何关闭连接,以使IIS在5s超时后无法发送回任何数据?

解决方法:

我终于能够通过使用原始套接字来复制问题,这是很多工作.使IIS记录已取消的请求的方法是在下面的代码中执行以下操作:

>不发送连接:关闭
>不要调用Socket.Dispose()

这是最终的工作代码,希望其他人会发现它有用:

private static void SocketTime(int readTimeout, Random random)
        {
            var ip = IPAddress.Parse("127.0.0.1");
            const int hostPort = 80;

            var hostep = new IPEndPoint(ip, hostPort);
            var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            sock.Connect(hostep);
            var uniqueID = random.Next().ToString();
            var get = $"GET http://localhost/api/apitest/testcancel/{uniqueID} HTTP/1.1\r\n" +
                      "x-apikey: somekey\r\n" +
                      "Host: foo.com\r\n" +
                      "Connection: Close\r\n" +
                      "\r\n";


            var getBytes = Encoding.UTF8.GetBytes(get);
            sock.ReceiveTimeout = readTimeout;
            sock.Send(getBytes);

            var responseData = new byte[1024];
            try
            {
                var bytesRead = sock.Receive(responseData);
                var responseString = new StringBuilder();
                while (bytesRead != 0)
                {
                    responseString.Append(Encoding.ASCII.GetChars(responseData), 0, bytesRead);
                    bytesRead = sock.Receive(responseData);
                }
                Console.WriteLine($"SUCCESS => Unique ID = {uniqueID}, Timeout = {readTimeout}");
            }
            catch (SocketException e)
            {
                if (e.SocketErrorCode == SocketError.TimedOut)
                {
                    Console.WriteLine($"FAIL => Unique ID = {uniqueID}, Timeout = {readTimeout}");
                }
                else
                {
                    Console.WriteLine("UNHNALDED ERROR: " + e.Message);
                }

            }
            finally
            {
                sock.Dispose();
            }
        }

标签:iis,dotnet-httpclient,c
来源: https://codeday.me/bug/20191119/2034861.html