简体   繁体   English

如何从asp.net进行异步web api调用?

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

I am trying to implement asynchronous web api call from asp.net 我正在尝试从asp.net实现异步web api调用

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. 我不想等待我的webapi电话完成。 How I can implement this using .net framework 4 ? 我如何使用.net框架4实现这一点?

Change the line to: 将行更改为:

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

Checking the Result property makes it synchronous. 检查Result属性使其同步。 Also make sure your method signature contains the async keyword. 还要确保您的方法签名包含async关键字。

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? 我如何使用.net框架4实现这一点?

You can't use async , await , or HttpClient on ASP.NET 4. They all require ASP.NET 4.5 . 您不能在ASP.NET 4上使用asyncawaitHttpClient 。它们都需要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 . 您可以选择升级到ASP.NET 4.5并使用自然await语法,或者继续使用ASP.NET 4并使用类似WebClient东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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