HttpClient PostAsync method throw Aggregate Exception

2.1k views Asked by At

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);

        }
    }
1

There are 1 answers

0
Emiel Koning On BEST ANSWER

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.