2017-05-31 58 views
0

我對asp和c#相對較新。我是如何(或在哪裏)調用我的異步操作方法

我有以下異步操作方法調用外部api並返回HttpResponseMessage。我希望它在運行時調用Index()動作方法時運行。我試圖從Index()內部調用它,但它說Index()應該是異步的,但我不知道如何使它異步,或者即時通訊做所有錯誤。

async static void PostRequest(string url, string userID, string accessKey, string djID, string artistName, string artistURL) 
    { 
     IEnumerable<KeyValuePair<string, string>> queries = new List<KeyValuePair<string, string>>() 
     { 
      new KeyValuePair<string, string>("UserID", userID), 
      new KeyValuePair<string, string>("AccessKey", accessKey), 
      new KeyValuePair<string, string>("DJID", djID), 
      new KeyValuePair<string, string>("ArtistName", artistName), 
      new KeyValuePair<string, string>("URL", artistURL) 
     }; 
     HttpContent q = new FormUrlEncodedContent(queries); 

     using (HttpClient client = new HttpClient()) 
     { 
      using (HttpResponseMessage response = await client.PostAsync(url, q)) 
      { 
       using (HttpContent content = response.Content) 
       { 
        string myContent = await content.ReadAsStringAsync(); 
        HttpContentHeaders headers = content.Headers; 
        System.Diagnostics.Debug.WriteLine(myContent); 
       } 

      } 
     } 
    } 
+0

請查看https://docs.microsoft.com/en-us/aspnet/mvc/overview/performance/using-asynchronous-methods-in-aspnet-mvc-4 – hardkoded

回答

1

您的操作方法應返回Task。這允許框架查看方法何時完成。

相關問題