简体   繁体   English

HttpClient PostAsync方法引发聚合异常

[英]HttpClient PostAsync method throw Aggregate Exception

I would like to use the http client class to call an api controller method and the PostAsync method has thrown an Aggregate Exception. 我想使用http客户端类调用api控制器方法,而PostAsync方法引发了Aggregate Exception。 I tried to write an async method what call the PostAsync and try the ContinueWith method but no one of them work. 我试图编写一个称为PostAsync的异步方法,然后尝试ContinueWith方法,但是没有一个起作用。 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) 这是我要调用的控制器:(我尝试了JsonResult,但也无法正常工作)

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

        }
    }

You could modify your getBack method like this. 您可以像这样修改getBack方法。 Since your endpoint is expecting parameters that are simple types (eg string or int), you need to wrap it in a FormUrlEncodedContent . 由于端点期望的参数是简单类型(例如,字符串或整数),因此需要将其包装在FormUrlEncodedContent The folderPath key in the Dictionary<string, string> corresponds with the name of the parameter of the endpoint. Dictionary<string, string>folderPath键与端点参数的名称相对应。

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")); 您甚至不需要client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); in your client, since you're not posting json. 在您的客户端中,因为您没有发布json。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM