Randeep Singh
Randeep Singh

Reputation: 1275

Post rest web api working from Postman but not returning any response from code in C# project

There is a POST rest api which used to work from code before. But recently it is broken and is not returning any response. However if I try to call the api from the Postman, then it works fine.

In what way can I debug this to find the root cause of the issue ?

Following is the C# code which I am using to call this post rest api

 public async Task SaveToServerAsync()
    {
        string filePath = @"<filePath>";
        ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
        // tried this line of code from another SO answer, but this didn't work either   
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://<server name>/");
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "d2ebf9aefbaa416adcd0");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Add("Accept", "*/*");
            client.DefaultRequestHeaders.Add("Connection", "keep-alive");

            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {
                var content = new MultipartFormDataContent();
                content.Add(new StreamContent(fileStream), "file", filePath);
                content.Add(new StringContent("e8d002f9-f381-44c2-bce0-13416929f14d"), "Id");

                try
                {
                    var response = await client.PostAsync("<rest api end point>", content).ConfigureAwait(false);

                    if (response.IsSuccessStatusCode)
                    {
                        Debug.Write("Response received");
                    }
                }
                catch (Exception ex)
                {
                    Debug.Write("Exception occured");
                    Debug.Write(ex.Message);
                }
                finally
                {
                }
            }
        }
    }

It always goes to the exception block with exception as "The task was cancelled"

Not sure how can I debug it when it anyway works from the Postman.

Upvotes: 0

Views: 3243

Answers (1)

Randeep Singh
Randeep Singh

Reputation: 1275

So the problem was related to ExpectContinue header which goes as true by default. Somehow server was not handling it properly and client was waiting for continue (100) message for indefinite time.

For the time being manually setting this header to be false worked for us:

httpClient.DefaultRequestHeaders.ExpectContinue = false;

Upvotes: 2

Related Questions