ASP.NET Core Web API - 如何向 HttpClient 添加连接超时

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

我正在我的 Asp.NET Core-6 应用程序中实现 HttpClient。我有如下所示的代码。

HttpProxyClient

public interface IHttpProxyClient
{
    Task<HttpTxnResponse> GetRequest(string resourcePath, string data, string mediaType, IDictionary<string, string> headerInfo);
    Task<HttpTxnResponse> PostRequest(string resourcePath, string data, string mediaType, IDictionary<string, string> headerInfo);
}

public class HttpProxyClient : IHttpProxyClient
{
    private readonly ILogger<HttpProxyClient> _logger;
    private static readonly HttpClient client = new HttpClient();
    public HttpProxyClient(ILogger<HttpProxyClient> logger)
    {
        _logger = logger;
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    }

    public async Task<HttpTxnResponse> PostRequest(string resourcePath, string data, string mediaType, IDictionary<string, string> headerInfo)
    {
        HttpTxnResponse responseFromServiceCall = new HttpTxnResponse();
        try
        {
            var request = new HttpRequestMessage(HttpMethod.Post, resourcePath);
            if (headerInfo != null)
            {
                foreach (var header in headerInfo)
                {
                    request.Headers.Add($"{header.Key}", $"{header.Value}");
                }
            }
            StringContent content = new StringContent(data, Encoding.UTF8, mediaType);
            request.Content = content;
            var result = await client.SendAsync(request);

            responseFromServiceCall.StatusCode = result.StatusCode.ToString();
            responseFromServiceCall.ResponseContent = await result.Content.ReadAsStringAsync();
            return responseFromServiceCall;
        }
        catch (Exception ex)
        {
            responseFromServiceCall.StatusCode = HttpStatusCode.InternalServerError.ToString();
            _logger.LogError(ex.Message);
        }


        return responseFromServiceCall;
    }

    public async Task<HttpTxnResponse> GetRequest(string resourcePath, string data, string mediaType, IDictionary<string, string> headerInfo)
    {
        HttpTxnResponse responseFromServiceCall = new HttpTxnResponse();
        try
        {
            string token = string.Empty;
            if (headerInfo != null)
            {
                foreach (var header in headerInfo)
                {
                    token = header.Value;
                }
            }

            client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", token);

            var result = await client.GetAsync(resourcePath);
            responseFromServiceCall.StatusCode = result.StatusCode.ToString();
            responseFromServiceCall.ResponseContent = await result.Content.ReadAsStringAsync();

        }
        catch (Exception ex)
        {
            responseFromServiceCall.StatusCode = HttpStatusCode.InternalServerError.ToString();
            _logger.LogError(ex.Message);
        }
        return responseFromServiceCall;
    }
}

下面是我调用 _httpProxyClient 的实现代码。这也显示在下面。

实施:

var httpResp = await _httpProxyClient.PostRequest(remoteUrl, payload, "application/json", headerInfo);

我想添加 30 秒连接超时。

我如何实现这一目标?还有我在哪里应用它?

谢谢

c# asp.net-core dotnet-httpclient
2个回答
0
投票

试试看(创建 httpclient 时);

private static readonly HttpClient client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };

或单独一行;

    private static readonly HttpClient client = new HttpClient();
    client.Timeout = TimeSpan.FromSeconds(30);

或者你可以看看“CancellationToken


0
投票
    public MyController()
    {
        // create HttpClient instance
        _httpClient = new HttpClient();

        // set connection timeout
        _httpClient.Timeout = TimeSpan.FromSeconds(10); // 10 seconds
    }

在上面的代码中,我们创建了一个 HttpClient 实例并将其 Timeout 属性设置为 10 秒。这意味着如果在 10 秒内无法建立连接,HttpClient 将抛出 TimeoutException。

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