0

I have the code below. Running it locally I get the response back from the API in under 1 second.

When I deploy it to a server, it's taking anywhere between 3 and 10 minutes to get the response!

I've deployed to 3 different servers with the same result. Any idea what might be wrong?

Below is my code:

string response = string.Empty; try { var content = new StringContent(JsonConvert.SerializeObject(request), System.Text.Encoding.UTF8, "application/json"); using (var client = new HttpClient()) { var responseMessage = client.PostAsync("https://myapi/createshorturl", content).Result; response = responseMessage.Content.ReadAsStringAsync().Result; return JsonConvert.DeserializeObject<CreateShortUrlResponse>(response); } } catch (Exception x) { return null; } 
9
  • 5
    You're using HttpClient wrong and You're (probably still) using HttpClient wrong Commented Nov 26, 2019 at 14:51
  • 1
    The server is on dial-up, the server is behind a slow proxy, and so on. We can't say anything about this, the code is irrelevant. Commented Nov 26, 2019 at 14:51
  • 1
    phuzi, to me that comment would be an "answer." Otherwise easily overlooked. Commented Nov 26, 2019 at 14:53
  • 4
    catch (Exception x) { return null;} ??? Are you sure you aren't receiving a lot of exceptions that are simply covered up? Commented Nov 26, 2019 at 14:57
  • 1
    @johnny5 my comment means to represent the start of a list of possible causes. There's simply too many. Commented Nov 26, 2019 at 15:01

2 Answers 2

2

It's likely you're using HttpClient wrong. Take a look at the following articles before continuing to use it:

TL;DR:

  • HttpClient holds on to the underlying socket far longer than you think.
  • Reuse HttpClient, do not create a new one for every request.
  • Use IHttpClientFactory
  • Don't .Result
Sign up to request clarification or add additional context in comments.

Comments

1

HttpClient instances should be reused, that should be your first stop to making changes here. Secondly, don't ever do Task.Result if you can avoid it. It is a synchronous call likely falling behind under load.

class Something { HttpClient client = new HttpClient(); public async Task<CreateShortUrlResponse> GetResponseAsync() { string response = string.Empty; try { var content = new StringContent(JsonConvert.SerializeObject(request), System.Text.Encoding.UTF8, "application/json"); { var responseMessage = await client.PostAsync("https://myapi/createshorturl", content); response = await responseMessage.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<CreateShortUrlResponse>(response); } } catch (Exception x) { //you should log something here, rather than silently returning null. Or let it propagate up to where it can be handled. return null; } } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.