barteloma
barteloma

Reputation: 6845

Asp.net mvc web api async request result

I have a web api controller action that sends a request to another server and gets an image.

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();
   }
}

How can I get async request result of requestMessage.SendAsync()

Upvotes: 1

Views: 873

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

You'll need to add the async modifier to the method and 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();
}

Or if you want the response inside Wms, you can await that.

Upvotes: 1

Related Questions