小编Ros*_*ech的帖子

为什么在 WebApi 上下文中在 using 块中使用 HttpClient 是错误的?

那么,问题是为什么在 using 块中使用 HttpClient 是错误的,但在 WebApi 上下文中呢?

我一直在阅读这篇文章“不要阻止异步代码”。其中我们有以下示例:

public static async Task<JObject> GetJsonAsync(Uri uri)
{
  // (real-world code shouldn't use HttpClient in a using block; this is just example code)
  using (var client = new HttpClient())
  {
    var jsonString = await client.GetStringAsync(uri);
    return JObject.Parse(jsonString);
  }
}

// My "top-level" method.
public class MyController : ApiController
{
  public string Get()
  {
    var jsonTask = GetJsonAsync(...);
    return jsonTask.Result.ToString();
  }
}
Run Code Online (Sandbox Code Playgroud)

评论// (real-world code shouldn't use HttpClient in a using …

c# using httpclient webapi

4
推荐指数
1
解决办法
2756
查看次数

标签 统计

c# ×1

httpclient ×1

using ×1

webapi ×1