Very slow HttpClient SendAsync call

After reading other answers I can’t realize why SendAsync is so slow.

Calling same endpoint from Postman, I got a response in 160ms.

Calling from the code below, takes 10 seconds. I’m using a c# desktop application to make the call.

public static async Task<string> GetToken()
{

    var url = "....";

    var dict = new Dictionary<string, string>();
    dict.Add("username", "foo");
    dict.Add("password", "bar");

    using (var client = new HttpClient(
        new HttpClientHandler
        {
            Proxy = null,
            UseProxy = false
        }))
    {
        //bypass SSL
        ServicePointManager.ServerCertificateValidationCallback = new
            RemoteCertificateValidationCallback
            (
                delegate { return true; }
            );
        var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(dict) };
        var res = await client.SendAsync(req); //10 seconds here!
        if (res.StatusCode != HttpStatusCode.OK)
            return string.Empty;

        var token = await JsonConvert.DeserializeObject<TokenResponse>(res.Content.ReadAsStringAsync());
        return token.access_token;
    }
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Your code is tangled and ignores IDisposable and this: HttpClient is intended to be instantiated once per application, rather than per-use.

Make reusable method for other-type requests

private static readonly HttpClient client = new HttpClient();

private async Task<T> PostDataAsync<T>(string url, Dictionary<string, string> formData)
{
    using (HttpContent content = new FormUrlEncodedContent(formData))
    using (HttpResponseMessage response = await client.PostAsync(url, content).ConfigureAwait(false))
    {
        response.EnsureSuccessStatusCode(); // throws if 404, 500, etc.
        string responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
        return JsonConvert.DeserializeObject<T>(responseText);
    }
}

Usage

public static async Task<string> GetToken()
{
    var url = "....";

    var dict = new Dictionary<string, string>();
    dict.Add("username", "foo");
    dict.Add("password", "bar");

    try
    {
        TokenResponse token = await PostDataAsync<TokenResponse>(url, dict);
        return token.access_token;
    }
    catch (HttpRequestException ex)
    {
        // handle Exception here
        return string.Empty;
    }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x