诡异的HttpClient
最近因为生成一个url二维码发现了C#HttpClient诡异的地方,先贴出代码:
private static async Task<string> GetShortUrlAsync(string url) { var client = new HttpClient(); client.DefaultRequestHeaders.Add("Token", "xxxxxx"); client.DefaultRequestHeaders.Add("ContentType", "application/json; charset=UTF-8"); var param = JsonConvert.SerializeObject(new { url }); var task = client.PostAsync("https://dwz.cn/admin/v2/create", new StringContent(param, Encoding.UTF8)); task.Wait(); var response = task.Result; //var response = await client.PostAsync("https://dwz.cn/admin/v2/create", new StringContent(param, Encoding.UTF8)); //卡在这里 var json = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeAnonymousType(json, new { Code = 0, ShortUrl = string.Empty, LongUrl = string.Empty, ErrMsg = string.Empty }); if (!string.IsNullOrEmpty(result.ErrMsg)) { throw new Exception(result.ErrMsg); } return result.ShortUrl; }
以上代码就是调用百度转短连接的API,就在异步获取Response的时候一直卡着不动,用task.Wait()再取task.Result就没问题,await语法以前用得很少,还请各位大神赐教