从Web方法中调用异步方法并获取返回

从Web方法中调用异步方法并获取返回

问题描述:

我在将一段工作代码移动到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

您可以在不使用异步内容的情况下完成此操作。

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