[英]HttpClient asynchronous Post C#
我有这行代码:
HttpResponseMessage aResponse = await aClient.PostAsync(theUri, theContent);
但是,我有一个错误:“await”运算符只能在异步方法中使用。 考虑使用'async'修饰符标记此方法并将其返回类型更改为'Task'。
所以我去搜索并找到了这个链接: HTTPClient异步POST和读取结果的故障排除
我已经尝试了答案,但我仍然得到了这个错误。 我该怎么办? 太感谢了
您需要使用async
修饰包含await
调用的方法,并在Task<TResult>
包装它的返回类型。 例如,如果您是从MVC中的Controller
的Index()
操作调用它,则必须修改:
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上的async(C#Reference) 。
当没有返回有意义的值和void
,还有返回Task
的情况,主要用于定义需要返回类型的事件处理程序。
对于所有可能的async
方法返回类型,请查看MSDN上的异步返回类型(C#和Visual Basic) 。
另外,这些操作需要在项目中引用System.Threading.Tasks
。
确保包含此行代码的方法标记为异步并返回Task对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.