Skip to main content
 首页 » 编程设计

c#之在 ASP.NET Web 表单中使用 .NET 4.5 HttpClient

2024年04月12日36jirigala

我想在 ASP.NET Web 窗体中使用 .NET 4.5 HttpClient 类。 我在 C# 5.0 in a NutShell 书中读到(第 663 页):

Unlike with WebClient, to get the best performance with HttpClient, you must reuse same instance (otherwise things such as DNS resolution may be unnecessarily repeated.) HttpClient permits concurrent operations, . . .

在我们的 ASP.NET web Form 网站中,我们需要连接到另一个网站。 我在 Application 属性中创建了一个 HttpClient 实例,以便在所有请求中使用单个实例。 在 Global.asax 中这样写:

Application.Add("MateCatWorker", new HttpClient()); 

我的问题是:这是一个好的做法吗?

请您参考如下方法:

根据HttpClient Class在 MSDN 上,这些方法是线程安全的:

  • CancelPendingRequests
  • DeleteAsyn
  • GetAsync
  • GetByteArrayAsync
  • GetStreamAsync
  • GetStringAsync
  • PostAsync
  • PutAsync
  • SendAsync

HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors. Below is an example using HttpClient correctly.

而且我建议不要将 HttpClient 存储到 Application 中,我不喜欢单例,但为此创建一个单例类要好得多。

public class GoodHttpClient 
{ 
    // OK 
    private static readonly _httpClient HttpClient; 
 
    static GoodHttpClient() 
    { 
        _httpClient = new HttpClient(); 
    } 
}