【问题标题】:C# HttpClient failing to make GET requests with Windows AuthenticationC# HttpClient 无法使用 Windows 身份验证发出 GET 请求
【发布时间】:2020-12-11 17:43:50
【问题描述】:

我有一个具有以下 HttpClient 配置的 .NET Core 3.1 Api 应用程序。在 Startup.cs 中

services.AddAuthentication(IISDefaults.AuthenticationScheme);

services.AddHttpClient("myapi", c =>
{
    c.BaseAddress = new Uri(Configuration["endpoint"]);
    c.DefaultRequestHeaders.Authorization =
       new AuthenticationHeaderValue(
          IISDefaults.AuthenticationScheme, Convert.ToBase64String(
             System.Text.Encoding.UTF8.GetBytes($"{Configuration["username"]}:{Configuration["password"]}")));
});

然后我尝试像这样进行 HTTP 调用:

var client = clientFactory.CreateClient(clientName);
HttpResponseMessage response = await client.GetAsync(url);            
if (response.IsSuccessStatusCode)            
    return await response.Content.ReadAsStringAsync(); 

但是,在调用内部 api 时,我总是得到未经授权的响应。在调试下,我启用了 Windows 身份验证和匿名身份验证。 使用 Postman,我的 api 调用会通过,这会验证我是否获得了正确的凭据。 你能提出任何改变来完成这项工作吗?

【问题讨论】:

    标签: asp.net-core windows-authentication dotnet-httpclient


    【解决方案1】:

    而不是c.DefaultRequestHeaders.Authorization =,我有这样的配置

    c.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
    {
      Credentials = new NetworkCredential("username", "password"),
      AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
      PreAuthenticate = true
    });
    

    我想这在你的情况下不会按原样工作,但我希望这能让你走上正轨。

    【讨论】:

      猜你喜欢
      • 2011-12-05
      • 1970-01-01
      • 2020-06-07
      • 1970-01-01
      • 2021-12-09
      • 2021-07-05
      • 2020-04-12
      • 2016-03-20
      • 1970-01-01
      相关资源
      最近更新 更多