gpt4 book ai didi

.net-core - HttpClient,UseDefaultCredentials,Windows身份验证,.NET Core 2.0+控制台应用程序收到401未经授权

转载 作者:行者123 更新时间:2023-12-04 01:15:30 29 4
gpt4 key购买 nike

我正在尝试从.NET Core 3.0控制台应用程序进行HTTP GET调用。端点需要Windows身份验证。终结点是IIS上的一种生产中的.NET Framework 4.5.2 Web API服务,已被多个客户端应用程序成功使用。

我的测试程序针对net45框架目标成功。相反,netcoreapp3.0构建收到401未经授权。

这是我的方法:

using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

static async Task<string> Get(string serverUri, string requestUri)
{
var handler = new HttpClientHandler() { UseDefaultCredentials = true };
var client = new HttpClient(handler) { BaseAddress = new Uri(serverUri) };
return await client.GetStringAsync(requestUri);
}

这是我的项目文件。

<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net45;netcoreapp3.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net45'">
<PackageReference Include="System.Net.Http" Version="4.3" />
</ItemGroup>
</Project>

运行 .\bin\Debug\net45\HttpClientTest.exe返回预期的JSON结果。

运行 dotnet .\bin\Debug\netcoreapp3.0\HttpClientTest.dll会收到“401未经授权”。
Unhandled exception. System.AggregateException: One or more errors occurred. (Response status code does not indicate success: 401 (Unauthorized).)
---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).
at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
at System.Net.Http.HttpClient.GetStringAsyncCore(Task`1 getTask)
at ConsoleApp1.Program.Get(String serverUri, String requestUri) in C:\temp\coreapp3\Program.cs:line 16
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at ConsoleApp1.Program.Main(String[] args) in C:\temp\coreapp3\Program.cs:line 22

我该如何解决?

我还尝试了以下变体,但输出没有任何变化:

handler.Credentials = CredentialCache.DefaultNetworkCredentials;
handler.Credentials = CredentialCache.DefaultCredentials;
handler.Credentials = new NetworkCredential(username, password, domain);

最佳答案

这个变通办法对我有用,在创建HttpClient / Handler之前添加它:

AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);

关于.net-core - HttpClient,UseDefaultCredentials,Windows身份验证,.NET Core 2.0+控制台应用程序收到401未经授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46306508/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com