C# HttpClient.GetAsync 与网络凭据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10292730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:13:23  来源:igfitidea点击:

HttpClient.GetAsync with network credentials

c#async-await.net-4.5

提问by Jan K.

I'm currently using HttpWebRequestto get a website. I'd like to use the await pattern, which is not given for HttpWebRequests. I found the class HttpClient, which seems to be the new Http worker class. I'm using HttpClient.GetAsync(...)to query my webpage. But I'm missing the option to add ClientCredentialslike HttpWebRequest.Credentials. Is there any way to give the HttpClientauthentication information?

我目前正在使用HttpWebRequest获取网站。我想使用 await 模式,但没有为HttpWebRequests. 我找到了 class HttpClient,它似乎是新的 Http worker 类。我正在使用HttpClient.GetAsync(...)查询我的网页。但我缺少添加ClientCredentialslike的选项HttpWebRequest.Credentials。有没有办法提供HttpClient认证信息?

采纳答案by dtb

You can pass an instance of the HttpClientHandler Classwith the credentials to the HttpClient Constructor:

您可以将带有凭据的HttpClientHandler 类的实例传递给HttpClient 构造函数

using (var handler = new HttpClientHandler { Credentials = ... })
using (var client = new HttpClient(handler))
{
    var result = await client.GetAsync(...);
}