![](/img/trans.png)
[英]PostAsync method of HttpClient throws an Aggregate exception after 2-3 timeout requests
[英]HttpClient PostAsync method throw Aggregate Exception
我想使用http客戶端類調用api控制器方法,而PostAsync方法引發了Aggregate Exception。 我試圖編寫一個稱為PostAsync的異步方法,然后嘗試ContinueWith方法,但是沒有一個起作用。 這是代碼:
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();
}
}
這是我要調用的控制器:(我嘗試了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);
}
}
您可以像這樣修改getBack
方法。 由於端點期望的參數是簡單類型(例如,字符串或整數),因此需要將其包裝在FormUrlEncodedContent
。 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();
}
您甚至不需要client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
在您的客戶端中,因為您沒有發布json。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.