我在 Azure Web 应用程序上托管了 ASP.NET Core 2.1 应用程序。我通过 WebSockets 发送照片 base64 字符串,然后通过 HttpClient 发送到 Azure Face API。

在大约 150-250 个请求之后 HttpClient 停止响应,我无法在我的应用程序的任何部分使用 HttpClient 类。

在我的本地主机中它工作正常,我从来没有遇到过这个问题。

public class FaceApiHttpClient
{
    private HttpClient _client;

    public FaceApiHttpClient(HttpClient client)
    {
        _client = client;
    }

    public async Task<string> GetStringAsync(byte[] byteData,string uri)
    {
        using (ByteArrayContent content = new ByteArrayContent(byteData))
        {
            content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            HttpResponseMessage response = await _client.PostAsync(uri, content).ConfigureAwait(false);

            return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
        }

    }
}

DI:
         services.AddHttpClient<FaceApiHttpClient>(
            client => {
                client.BaseAddress = new Uri("xxx");
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "xxx");
            });

FaceApiClient 中的方法在 Scoped Service 中调用:
public interface IFaceAPIService
{
    Task<DataServiceResult<List<Face>>> GetFacesDataFromImage(byte[] byteArray);
}

public class FaceAPIService: ServiceBase, IFaceAPIService
{
    private readonly IServerLogger _serverLogger;
    private FaceApiHttpClient _httpClient;
    //Consts
    public const string _APIKey = "xxx";
    public const string _BaseURL = "xxx";

    public FaceAPIService(IServerLogger serverLogger, FaceApiHttpClient client)
    {
        _serverLogger = serverLogger;
        _httpClient = client;
    }

    public async Task<DataServiceResult<List<Face>>> GetFacesDataFromImage(byte[] byteData)
    {
        try
        {
            // Request parameters. A third optional parameter is "details".
            string requestParameters = "returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise";

            // Assemble the URI for the REST API Call.
            string uri = _BaseURL + "/detect" + "?" + requestParameters;
            var result = await _httpClient.GetStringAsync(byteData, uri).ConfigureAwait(false);
            List<Face> faces = JsonConvert.DeserializeObject<List<Face>>(result);
            return Success(faces);

        }
        catch (Exception ex)
        {
            _serverLogger.LogExceptionFromService(ex);
            return DataServiceResult.ErrorResult<List<Face>>(ex.Message);
        }
    }
}

a) 在 localhost 环境下它可以工作。我运行了 11 个模拟器,每秒有很多请求,而且它从未中断(10 小时的模拟器,超过 20k 的请求)。

b) HttpClient 在应用程序的任何部分停止工作,而不仅仅是在一个类中。

如何解决这个问题?

最佳答案

考虑稍微改变一下设计。

使用类型化客户端的假设是它的配置不会经常更改,并且应该在注册类型化客户端时添加一次。

services.AddHttpClient<FaceApiHttpClient>(_ => {
    _.BaseAddress = new Uri(Configuration["OcpApimBaseURL"]);
    var apiKey = Configuration["OcpApimSubscriptionKey"];
    _.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", apiKey);
    _.Timeout = new TimeSpan(0, 0, 10);
});

这将允许键入的客户端不必为每次调用添加 key
public class FaceApiHttpClient {
    private readonly HttpClient client;

    public FaceApiHttpClient(HttpClient client) {
        this.client = client;
    }

    public async Task<string> GetStringAsync(byte[] byteData, string uri) {
        using (var content = new ByteArrayContent(byteData)) {
            // This example uses content type "application/octet-stream".
            // The other content types you can use are "application/json" and "multipart/form-data".
            content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            // Execute the REST API call.
            HttpResponseMessage response;  response = await _client.PostAsync(uri, content).ConfigureAwait(false);

            // Get the JSON response.
            return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
        }
    }
}

应该从 ASP.NET Core 2.1-preview1: Introducing HTTPClient factory 注意到



根据之前的文档,创建这么多客户端可能会带来问题,但这里的假设是此新功能的开发人员在设计时已考虑到这一点。

我这样说是因为您描述的问题类似于具有相同原因的先前问题。

关于c# - ASP .NET Core 2.1-preview2 HttpClient 死锁,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49831568/

10-17 02:25