HttpClient asynchronous Post C#

本文关键字:Post asynchronous HttpClient | 更新日期: 2023-09-27 18:35:35

我有这样一行代码:

HttpResponseMessage aResponse = await aClient.PostAsync(theUri, theContent);

但是,我有一个错误说:"await"运算符只能在异步方法中使用。请考虑使用"异步"修饰符标记此方法,并将其返回类型更改为"Task"。

所以我去搜索并找到了这个链接:对HTTPClient 异步 POST 和读取结果进行故障排除

我已经尝试了答案的作用,但我仍然收到该错误。我该怎么办?谢谢一百万

HttpClient asynchronous Post C#

您需要

async修饰包含await调用的方法,并将其返回类型包装在Task<TResult>中。例如,如果从 MVC 中ControllerIndex()操作调用它,则必须修改:

public ActionResult Index() 
{
    HttpResponseMessage aResponse = await aClient.PostAsync(theUri, theContent);
    //will give you the error you are getting
}

..所以它变成了:

public async Task<ActionResult> Index() 
{
    HttpResponseMessage aResponse = await aClient.PostAsync(theUri, theContent);
    //no error here
}

查看 MSDN 上的异步(C# 参考)。

还有一种情况是,当没有返回有意义的值时返回Taskvoid,主要用于定义事件处理程序,这需要该返回类型。

有关async方法的所有可能的返回类型,请查看 MSDN 上的异步返回类型(C# 和 Visual Basic)。

顺便说一句,这些操作需要在项目中引用System.Threading.Tasks

确保包含此代码行的方法标记为异步并返回 Task 对象。

http://msdn.microsoft.com/en-us/library/hh156513.aspx