Search code examples
c#asp.net-coredotnet-httpclient

ASP.NET Core Web API - How to add connection timeout to HttpClient


I am implementing HttpClient in my Asp.NET Core-6 Application. I have this code as shown below.

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;
    }
}

Then below I have the code for the implementation where I called the _httpProxyClient. This is also show below.

Implementation:

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

I want to add 30 seconds connection timeout.

How do I achieve this? And Also where do I apply it?

Thanks


Solution

  • Try that (when creating httpclient);

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

    or in a separate line;

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

    or you can have a look "CancellationToken"