我正在尝试从.NET Core 2.0控制台应用程序进行HTTP GET调用。端点需要Windows身份验证。
我的测试程序成功实现net45
框架目标。相反,netcoreapp2.0
版本会收到401 Unauthorized。
这是我的方法:
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;netcoreapp2.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)' != 'netcoreapp2.0'">
<PackageReference Include="System.Net.Http" Version="4.3" />
</ItemGroup>
</Project>
运行.\bin\Debug\net45\HttpClientTest.exe
会返回预期的JSON结果。
正在运行dotnet .\bin\Debug\netcoreapp2.0\HttpClientTest.dll
会收到401 Unauthorized。
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>d__27.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at HttpClientTest.Program.<Get>d__1.MoveNext() in C:\temp\HttpClientTest\Program.cs:line 24
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at HttpClientTest.Program.Main(String[] args) in C:\temp\HttpClientTest\Program.cs:line 16
如何解决此问题?
我也尝试过以下变化,但输出没有任何变化:
handler.Credentials = CredentialCache.DefaultNetworkCredentials;
handler.Credentials = CredentialCache.DefaultCredentials;
handler.Credentials = new NetworkCredential(username, password, domain);
答案 0 :(得分:1)
此变通办法适用于我,在创建HttpClient /处理程序之前将其添加:
web: npm run dev
答案 1 :(得分:-2)
所以我们遇到了与HttpClient相同的问题,但是在第一次请求时它是未经授权的,但如果我们再做一个快速请求调用,它会很好地通过,我们会获得授权。
如果我在.NET 4.7.1控制台应用程序上执行此操作,它可以完美运行。如果我在.NET 4.7.1空Web应用程序中执行此操作,它可以正常工作,只有当我执行.NET Core 2.x时才能解决此问题。
var result = string.Empty;
var responseMessage = _client.GetAsync(url).Result;
if (responseMessage.IsSuccessStatusCode)
{
result = await responseMessage.Content.ReadAsStringAsync();
}
else
{
var responseMessage2 = _client.GetAsync(url).Result;
if (responseMessage2.IsSuccessStatusCode)
{
result = await responseMessage2.Content.ReadAsStringAsync();
}
}
return result;