2014-10-20 135 views
1

我在將一段工作代碼移動到Web方法時遇到困難。我在玩SteamAPI和異步方法RunAsync(),它都是以前工作的時候,它都是在代碼隱藏中處理的。從Web方法中調用異步方法並獲取返回

但我想把這個動作轉換成一個Web方法,由JQuery.AJAX()處理。我基本上是從Web方法中調用該方法,並希望將數據回傳給JQuery來處理/表示。我之前處理過很多Web方法,但都沒有調用非靜態方法和異步方法。

我實際上並沒有收到錯誤,但在調用API時,它只是坐在那裏,我可以看到它請求fiddler中的數據(並返回它),但它從不會從這一點繼續前進,就像它還沒有收到'我有我的數據'的命令。最終,我的.ajax電話會在30秒後耗盡。

任何人都可以看到爲什麼?我放置了一定的中斷點,但是它從來不會從

string res = await client.GetStringAsync("IPlayerService/GetOwnedGames/v0001/?key=my_steam_key&steamid=my_steam_id&include_appinfo=1&include_played_free_games=1&format=json"); 

即使在小提琴手顯示出現了響應。

請參閱代碼和截圖。

[System.Web.Services.WebMethod] 
    public static async Task<string> Find_Games(string user) 
    { 
     string rVal = string.Empty; 
     dynamic user_game_data; 

     try 
     { 
      var thisPage = new _default(); 
      user_game_data = await thisPage.RunAsync(); 

      return user_game_data; 
     } 
     catch (Exception err) 
     { 
      throw new Exception(err.Message); 
     } 

    } 


    public async Task<string> RunAsync() 
    { 
     using (var client = new HttpClient()) 
     { 
      client.BaseAddress = new Uri("http://api.steampowered.com/"); 
      client.DefaultRequestHeaders.Accept.Clear(); 
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
      //client.Timeout = System.TimeSpan.FromMilliseconds(15000); //15 Secs 

      try 
      { 
       string res = await client.GetStringAsync("IPlayerService/GetOwnedGames/v0001/?key=my_steam_key&steamid=my_steam_id&include_appinfo=1&include_played_free_games=1&format=json"); 

       // Read & Deserialize data 
       //dynamic json_data = JsonConvert.DeserializeObject(res); 
       ////int gamecount = json_data.response.game_count; 
       //await saveOwnedGames(json_data, gamecount); 
       return res; 
      } 
      catch (HttpRequestException e) 
      { 
       throw new Exception(e.Message); 
      } 

     } 
    } 

Fiddler Response, which i can examine the returned json data

在此先感謝,讓我知道如果你需要任何更多的信息。

+0

您是否嘗試過調試代碼? – 2014-10-20 16:04:34

+0

當然可以,但它不會返回錯誤。在調用Runasync()之後,它只是坐在那裏,直到ajax調用超時。就像我上面提到的,在Fiddler工作時,我可以觀察呼叫,以及來自呼叫的返回數據。它似乎沒有對返回的數據做任何事情。 – JGreasley 2014-10-20 16:12:12

+0

@JGreasley嘗試在瀏覽器中打開您的http://api.steampowered.com/I ... URL(使用您正在使用的所有查詢字符串參數)並查看它是否返回任何內容,也許這只是一個錯誤的請求。 – fooser 2014-10-20 16:14:22

回答

0

您可以在不使用異步內容的情況下完成此操作。

WebClient一試:

[System.Web.Services.WebMethod] 
public static string Find_Games(string user) 
{ 
    using (var client = new System.Net.WebClient()) 
    { 
     return client.DownloadString(String.Concat("http://api.steampowered.com/", "IPlayerService/GetOwnedGames/v0001/?key=my_steam_key&steamid=my_steam_id&include_appinfo=1&include_played_free_games=1&format=json")); 
    } 
} 
+0

完美 - 感謝您的所有幫助夥計。 – JGreasley 2014-10-20 17:03:15

+1

針對異步代碼問題的解決方案不是同步重寫它。 – supertopi 2014-10-21 16:39:03