c# - 如何让 HttpClient 随请求一起传递凭据?

标签 c# asp.net-web-api impersonation windows-security

我有一个与 Windows 服务对话的 Web 应用程序(托管在 IIS 中)。 Windows 服务使用 ASP.Net MVC Web API(自托管),因此可以使用 JSON 通过 http 进行通信。 Web 应用程序配置为进行模拟,其想法是向 Web 应用程序发出请求的用户应该是 Web 应用程序用来向服务发出请求的用户。结构如下所示:

(以红色突出显示的用户是以下示例中提到的用户。)


Web 应用程序使用 HttpClient 向 Windows 服务发出请求:

var httpClient = new HttpClient(new HttpClientHandler() 
                      {
                          UseDefaultCredentials = true
                      });
httpClient.GetStringAsync("http://localhost/some/endpoint/");

这向 Windows 服务发出请求,但没有正确传递凭据(该服务将用户报告为 IIS APPPOOL\ASP.NET 4.0)。 这不是我想要发生的事情

如果我将上面的代码更改为使用 WebClient相反,用户的凭据被正确传递:

WebClient c = new WebClient
                   {
                       UseDefaultCredentials = true
                   };
c.DownloadStringAsync(new Uri("http://localhost/some/endpoint/"));

使用上述代码,服务将用户报告为向 Web 应用程序发出请求的用户。

我在 HttpClient 实现上做错了什么导致它无法正确传递凭据(或者它是 HttpClient)?

我想使用 HttpClient 的原因是它有一个与 Task 配合良好的异步 API,而 WebClient 的 asyc API 需要用事件来处理。

最佳答案

您可以将 HttpClient 配置为自动传递凭证,如下所示:

var myClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });

关于c# - 如何让 HttpClient 随请求一起传递凭据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12212116/

相关文章:

c# - 是否可以在 Azure DevOps 中使用 Coverlet 获得 .NET Framework 项目的代码覆盖率?

c# - ASP.NET Core 2.0 Web API IIS 托管和调试

c# - 模拟时使用 OpenFileDialog 访问映射的驱动器

c# - 模拟在 Powershell 中使用 WindowsIdentity 抛出 FileNotFoundException

c# - 使用 ManualResetEventSlim 而不是 ManualResetEvent 的最短等待时间是多少?

c# - RandomNumberGenerator 的正确使用

c# - System.Web.Http.AuthorizeAttribute 无法识别自定义角色提供者

asp.net - 设置 validateIntegratedModeConfiguration=false 以继续使用身份 impersonate=true 是否安全?

C# HTMLAgilityPack 获取内容 <script>

asp.net-web-api - ASP.NET Core,以查询字符串为模板的 Web API RouteAttribute