C# HttpClient 无法使用 Windows 身份验证发出 GET 请求
C# HttpClient failing to make GET requests with Windows Authentication
我有一个 .NET Core 3.1 Api 应用程序具有以下 HttpClient 配置。在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 呼叫通过,这验证了我获得了正确的凭据。
你能建议任何改变来使这项工作吗?
而不是 c.DefaultRequestHeaders.Authorization =
,我有这样的配置
c.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
Credentials = new NetworkCredential("username", "password"),
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
PreAuthenticate = true
});
我想这在您的情况下不会像现在这样工作,但我希望这能让您走上正轨。
我有一个 .NET Core 3.1 Api 应用程序具有以下 HttpClient 配置。在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 呼叫通过,这验证了我获得了正确的凭据。 你能建议任何改变来使这项工作吗?
而不是 c.DefaultRequestHeaders.Authorization =
,我有这样的配置
c.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
Credentials = new NetworkCredential("username", "password"),
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
PreAuthenticate = true
});
我想这在您的情况下不会像现在这样工作,但我希望这能让您走上正轨。