在我的 ASP.NET MVC 应用程序中重用 HttpClient 实例

问题描述 投票:0回答:1

我正在 .NET 4.8 上使用 ASP.NET MVC 应用程序。在此过程中,我使用了来自三个不同合作伙伴的 API。每次进行 API 调用时,都会在控制器中创建

HttpClient
的新实例,并通过视图页面的 ajax 调用进行调用。

我的问题是,即使我们可以使用像 UNITY 这样的第三方包进行开发,我们也无法创建依赖注入,因为这是一个 ASP.NET MVC 应用程序而不是 ASP.NET Core 应用程序。

如何在程序中重用

HttpClient
实例而不是利用依赖注入?

由于大多数文章都提到性能不佳和套接字耗尽是由于建立新的

HttpClient
实例而导致的。这是我的 API 调用代码,并且考虑到这个 API 在一天中会被大量调用。

代码:

var client = new HttpClient();
HttpResponseMessage response = null;

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Ssl3
                        | System.Net.SecurityProtocolType.Tls
                        | System.Net.SecurityProtocolType.Tls11
                        | System.Net.SecurityProtocolType.Tls12;

var content = JsonConvert.SerializeObject(ModelObj, settings);
byte[] buffer = Encoding.ASCII.GetBytes(content);
var bytecontent = new ByteArrayContent(buffer);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

response = client.PostAsync(URL,bytecontent).Result;

我需要在整个应用程序中重用

HttpClient
实例,而不在 .NET 4.8 上的 ASP.NET MVC 中使用依赖项容器。

asp.net-mvc dotnet-httpclient .net-4.8
1个回答
0
投票

您可以实现像 Singleton 模式这样的模式来在应用程序中管理和重用

HttpClient
实例。

创建一个管理

HttpClient
实例的静态类:

public static class HttpClientHelper
{
    private static readonly Lazy<HttpClient> httpClientInstance = new Lazy<HttpClient>(() =>
    {
        var httpClient = new HttpClient();

        // Set your desired SecurityProtocol
        System.Net.ServicePointManager.SecurityProtocol =
            System.Net.SecurityProtocolType.Tls12 | 
            System.Net.SecurityProtocolType.Tls11 | 
            System.Net.SecurityProtocolType.Tls;

        return httpClient;
    });

    public static HttpClient GetInstance()
    {
        return httpClientInstance.Value;
    }
}

然后,在您的控制器中或任何进行 API 调用的地方,您可以使用此

HttpClientHelper
类来获取单例
HttpClient
实例:

var client = HttpClientHelper.GetInstance();
var content = JsonConvert.SerializeObject(ModelObj, settings);
byte[] buffer = Encoding.ASCII.GetBytes(content);
var bytecontent = new ByteArrayContent(buffer);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var response = client.PostAsync(URL, bytecontent).Result;

请注意,上述代码可以帮助解决与创建多个实例相关的问题,但您必须正确处理

HttpClient
,包括管理其生命周期并确保不再需要时进行正确处置。

© www.soinside.com 2019 - 2024. All rights reserved.