0

I would like to use the http client class to call an api controller method and the PostAsync method has thrown an Aggregate Exception. I tried to write an async method what call the PostAsync and try the ContinueWith method but no one of them work. Here is the code:

class Program
{
    private const string apiPath = @"http://localhost:51140";
    private const string param = "/Home/savedocumenttoPath?folderPath=string";

    static void Main(string[] args)
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(apiPath);

        // Add an Accept header for JSON format.
        client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = getBack(client);

        Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);

        client.Dispose();
        Console.ReadLine();
    }

    public static HttpResponseMessage getBack(HttpClient client)
    {
         return client.PostAsync(client.BaseAddress + param, null).GetAwaiter().GetResult();
    }
}

And here is the controller what I want to call:(I tried JsonResult but that also not work)

[HttpPost]
    public ActionResult saveDocumentToPath(string folderPath)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(folderPath)) throw new NullReferenceException("Invalid Folder!");
            var fullPath = folderPath + "\\";
            if (!System.IO.Directory.Exists(fullPath))
            {
                return new HttpStatusCodeResult(HttpStatusCode.OK, "The specified directory not exists: \n" + fullPath);
            }

            var fileName = "ProjectList_Excel_" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day;

            var filePathName = fullPath + fileName;
            if (System.IO.File.Exists(filePathName))
            {
                return new HttpStatusCodeResult(HttpStatusCode.OK, "The specified file already exists in the folder: \n" + fileName);
            }
            System.IO.File.WriteAllBytes(filePathName, BL.ExcelExport.GetProjectListExcel());

            return new HttpStatusCodeResult(HttpStatusCode.OK, "File Exported successfully!");
        }
        catch (Exception e)
        {
            return new HttpStatusCodeResult(HttpStatusCode.OK, "Error occured while saving the file" + e.Message);

        }
    }
Dan Def
  • 1,836
  • 2
  • 21
  • 39
  • 3
    When debugging, you can look at the `InnerExceptions` of the aggregate exception to find the actual root cause of the issue – Ramesh Jan 31 '19 at 08:21
  • As a troubleshooting step, the first thing I would do is check whether the server received any traffic to begin with. If it didn't, there is something up with your client code or your network connection. – John Wu Jan 31 '19 at 08:23
  • 1
    Also, if you catch the aggregrate exception you can call `Flatten()` on it to get a single instance – Fermin Jan 31 '19 at 08:25

1 Answers1

0

You could modify your getBack method like this. Since your endpoint is expecting parameters that are simple types (e.g. string or int), you need to wrap it in a FormUrlEncodedContent. The folderPath key in the Dictionary<string, string> corresponds with the name of the parameter of the endpoint.

public static HttpResponseMessage getBack(HttpClient client)
{
    var values = new Dictionary<string, string>
    {
        { "folderPath", @"C:\Temp" }
    };

    var content = new FormUrlEncodedContent(values);

    return client.PostAsync("Home/saveDocumentToPath", content).GetAwaiter().GetResult();
}

You won't even need the client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); in your client, since you're not posting json.

Emiel Koning
  • 4,039
  • 1
  • 16
  • 18