HttpClient, UseDefaultCredentials, Windows Authent

2019-04-05 23:22发布

I am trying to make an HTTP GET call from a .NET Core 2.0 console application. The endpoint expects Windows Authentication.

My test program succeeds for a net45 framework target. In contrast, the netcoreapp2.0 build receives a 401 Unauthorized.

Here is my method:

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);
}

Here is my project file.

<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>

Running .\bin\Debug\net45\HttpClientTest.exe returns the expected JSON result.

Running dotnet .\bin\Debug\netcoreapp2.0\HttpClientTest.dll receives a 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

How do I fix this?

I have also tried the variations below, without any change in output:

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

1条回答
你好瞎i
2楼-- · 2019-04-05 23:54

So we are running into the same issue with HttpClient, but on the first request it is unauthorized, but if we do a another quick request call, it goes through just fine, and we get authorized.

If I do this on a .NET 4.7.1 console app, it works perfect. If I do it in a .NET 4.7.1 empty web app, it works fine, only if I do .NET Core 2.x do we get this issue.

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;
查看更多
登录 后发表回答