-1

I am getting this error when I call add "await" keyword and getting output when I remove "await" keyword

Code:

 public class ApiHelper : IApiHelper
    {
        private const int APiRetryCount = 4;

        private static HttpClient client = new HttpClient();


        public async Task<string> PostAsync<T>(T payload, string apiEndpoint)
        {
            for (int i = 0; i < APiRetryCount; i++)
            {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.BaseAddress = new Uri("http://app-et-csswrapperapi-dev.azurewebsites.net/");
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + token.AccessToken);
                    
                    var content = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json");
                    var response = **await** client.PostAsync(apiEndpoint, content);
            }

            // if we got here, we have maxed out retry count and got transient failures or are not authorized
            // log warning
            return default(string);
        }
    }

I am getting exception: Sys.WebForms.PageRequestManagerTimeoutException: Sys.WebForms.PageRequestManagerTimeoutException: The server request timed out

But when I replace the line

var response = **await** client.PostAsync(apiEndpoint, content);

with below code, its working fine:

var response = client.PostAsync(apiEndpoint, content).Result;

My doubt is what its making a big difference between await and .Result() ??

Avinash
  • 79
  • 1
  • 7

1 Answers1

0

There is nothing wrong with your code. This is the way to go var response = await client.PostAsync(apiEndpoint, content);. I suspect you are running into a deadlock in the code outside the method PostAsync. Make sure you use await when you call it: await PostAsync<SomeClass>(instance,"/api/endpoint"); and that you use async/await all the way up to the controller.

Edit: you can check this answer too: https://stackoverflow.com/a/15022170/1817574