HttpClient fix memory leaks on massive requests


 .NET Framework >  Http, Ftp


services.AddHttpContextAccessor();

services.AddTransient<ResponseLifetimeScopeHandler>();

builder.AddHttpMessageHandler<ResponseLifetimeScopeHandler>();

 

var builder = services

    .AddHttpClient(typeof(TControllerInterface).Name, (sp, c) =>

    {

        c.DefaultRequestHeaders.ConnectionClose = true;

        c.DefaultRequestHeaders.ExpectContinue = false;

    });

 

builder.ConfigurePrimaryHttpMessageHandler(() =>

{

       var httpClientHandler = new HttpClientHandler();       

       httpClientHandler.UseProxy = false;

       httpClientHandler.Proxy = null;

       return httpClientHandler;

 

});

********

 

public class ResponseLifetimeScopeHandler : DelegatingHandler

{

       private readonly IHttpContextAccessor _httpContextAccessor;

       private HttpResponseMessage _httpResponseMessage;

       public ResponseLifetimeScopeHandler(IHttpContextAccessor httpContextAccessor)

       {

             _httpContextAccessor = httpContextAccessor;

       }

       protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)

       {

             _httpResponseMessage = await base.SendAsync(request, cancellationToken);

             _httpContextAccessor.HttpContext.Response.RegisterForDispose(request);

             _httpContextAccessor.HttpContext.Response.RegisterForDispose(_httpResponseMessage);

             return _httpResponseMessage;

       }

}


15.11.2019 15:58   alexander.surbashev  

Великолепно

Оставлять комментарии могут только зарегистрированные пользователи
Дата создания: 15.11.2019 15:05
Дата изменения: 22.11.2019 10:15
Автор: admin