C#如何将HttpClient保持活动设置为false [英] C# How to set HttpClient Keep-Alive to false

查看:850
本文介绍了C#如何将HttpClient保持活动设置为false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.NET上的HTTP请求存在性能低下的问题。对本地主机上的REST API的HTTP GET请求大约花费了500毫秒来完成。我花了很多时间来修复它。我尝试了很多方法: HttpClient HttpWebRequest WebClient RestSharp 。他们都不工作。互联网上大多数解决方案都说将 Proxy 参数设置为 null ,但是它仍然无法更快地工作。

I had a low performance problem with HTTP requests on .NET. The HTTP GET request to a REST API on the localhost took about 500 ms to complete. I spent a lot of time to fix it. I have tried many ways: HttpClient, HttpWebRequest, WebClient and RestSharp. None of them work. Most solutions on the Internet said to set Proxy parameter to null but it still won't work faster.

我发现减少此时间的唯一方法是将request的Keep-Alive参数设置为false:

The only way I found to reduce this time is to set the Keep-Alive parameter of request to false:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
request.KeepAlive = false;

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

这很好。时间减少到7-10毫秒。但是现在由于某些原因,我需要使用 HttpClient 而不是 HttpWebRequest 。而且我找不到如何为 HttpClient 将Keep-Alive设置为false。我发现的唯一一件事就是如何通过将连接标头设置为保持活动来将其设置为true。

This works great. Time is reduced to 7-10 ms. But now in some reasons I need to use HttpClient instead of HttpWebRequest. And I can't find how to set Keep-Alive to false for HttpClient. The only thing I found is how to set it to true by setting a "connection" header to "Keep-Alive".

我正在使用此代码通过POST请求HttpClient:

I am using this code for POST request by HttpClient:

        HttpClient _http = new HttpClient();
        _http.DefaultRequestHeaders.Accept.Clear();
        _http.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
        _http.DefaultRequestHeaders.Add("Keep-Alive", "timeout=600");

        var content = new StringContent(
            request, Encoding.UTF8, "application/%appname%+xml");
        content.Headers.ContentType.Parameters.Add(
            new NameValueHeaderValue("type", "payload"));

        HttpResponseMessage response = await _http.PostAsync(uri, content);

并且仍然需要大约500-600毫秒才能完成。

And it still takes about 500-600 ms to complete.

推荐答案

设置 HttpWebRequest.KeepAlive = true 时,标头设置为 Connection:keep-alive

设置 HttpWebRequest.KeepAlive = false 时,标头设置为连接:关闭

因此您将需要

_http.DefaultRequestHeaders.Add("Connection", "close");

这篇关于C#如何将HttpClient保持活动设置为false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆