Asp.net mvc web api异步请求结果

时间:2015-06-16 11:38:41

标签: c# asp.net asp.net-mvc async-await

我有一个web api控制器操作,它将请求发送到另一台服务器并获取图像。

public class MyController : ApiController
{ 
   public async Runner<HttpResponseMessage> Wms()
   {
       return await Run();                                    
   }

   private Task<HttpResponseMessage> Run()
   {
       HttpRequestMessage requestMessage = new HttpRequestMessage();
       requestMessage.RequestUri = "http://....";

       foreach (var header in this.Request.Headers)
          requestMessage.Headers.Add(header.Key, header.Value);

        return requestMessage.SendAsync();
   }
}

如何获取requestMessage.SendAsync()

的异步请求结果

1 个答案:

答案 0 :(得分:1)

您需要将async修饰符添加到方法await SendAsync()

private async Task<HttpResponseMessage> RunAsync()
{
   HttpRequestMessage requestMessage = new HttpRequestMessage();
   requestMessage.RequestUri = "http://....";

   foreach (var header in this.Request.Headers)
      requestMessage.Headers.Add(header.Key, header.Value);

   HttpResponseMessage response = await requestMessage.SendAsync();
   string resultData = await response.Content.ReadAsStringAsync();
}

或者如果您想要Wms内的回复,可以await那个。