如何将WebClient替换为HttpClient?

30
我在我的ASP.NET MVC Web应用程序中有以下WebClient:
using (WebClient wc = new WebClient()) // call the Third Party API to get the account id 
{
     string url = currentURL + "resources/" + ResourceID + "/accounts?AUTHTOKEN=" + pmtoken;
     var json = await wc.DownloadStringTaskAsync(url);
 }

请问有谁能指导我如何将代码中的 WebClient 更改为 HttpClient 吗?


5
现在所有酷炫的孩子都在使用 HttpClient。它是 WebRequest 的封装并提供更易于使用的模型。 - Ananke
1
@Ananke,你能否给予建议如何将WebClient更改为HttpClient? - John John
1个回答

43
// Injecting HttpClient would be a better idea if possible
HttpClient client = new();
string page = await client.GetStringAsync("page URL here");

谢谢回复,但是如果我在你的代码中用await替换.Result,会有任何问题吗? - John John
1
@johnG 请查看更新后的答案,以处理'await'而不是'Result'属性。 - Hakan Fıstık
1
@johnG 我也为 'WebRequest' 类添加了一个更新。 - Hakan Fıstık
谢谢回复,但为什么建议使用 HttpClient,我没有理解您的观点.. 谢谢... - John John
7
在使用 HttpClient 时,不要将其放在 using 块中。这样做是错误的。请参阅下面的链接,了解详细说明。简而言之,HttpClient 被设计为在整个应用程序中使用单个实例。它会处理打开和关闭套接字的操作。如果将其包装在 using 块中,则会在后续被释放,并且无法像预期那样关闭套接字。这可能导致系统在达到每秒请求的某个阈值后耗尽套接字。https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ - Anthony Stivers
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接