简体   繁体   中英

HttpClient asynchronous Post C#

I have this line of code:

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

However, I have an error that says: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

So I went to search and found this link: Troubleshooting HTTPClient asynchronous POST and reading results

I've tried what the answer does, but I still get that error. What should I do? Thanks a million

You need to decorate the method containing the await call with async and wrap it's return type in Task<TResult> . For example, if you were calling it from an Index() action of a Controller in MVC, you would have to modify:

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

..so it becomes:

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

Have a look at async (C# Reference) on MSDN.

There's also the case of returning Task when no meaningful value is returned and void , used primarily to define event handlers, which require that return type.

For all the possible return types of async methods, have a look at Async Return Types (C# and Visual Basic) on MSDN.

As an aside, these operations require referencing System.Threading.Tasks in your project.

Make sure that the method containing this line of code is marked async and returns a Task object.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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