简体   繁体   中英

How to make a asynchronous web api call from asp.net?

I am trying to implement asynchronous web api call from asp.net

My code is similar like this

var response = httpClient.PostAsJsonAsync("api/apicontroller/execute/", executeModel).Result;

This is working in synchronous mode .

I do not want to wait for my webapi call to complete. How I can implement this using .net framework 4 ?

Change the line to:

var response = await httpClient.PostAsJsonAsync("api/apicontroller/execute/", executeModel);

Checking the Result property makes it synchronous. Also make sure your method signature contains the async keyword.

edit: If you don't want to wait for the result right away, you can postpone the await like this (or never perform it):

var task = httpClient.PostAsJsonAsync("api/apicontroller/execute/", executeModel);
/* Do other stuff in parallell here */
var result = await task;

How I can implement this using .net framework 4?

You can't use async , await , or HttpClient on ASP.NET 4. They all require ASP.NET 4.5 . Your options are to upgrade to ASP.NET 4.5 and use the natural await syntax or to stay on ASP.NET 4 and use something like WebClient .

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