Exception thrown when setting HttpClientHandler cr

2019-08-02 00:51发布

问题:

I know that this is technically still a preview, and this might be a known (or unknown) issue but I could also be missing something obvious (especially as not being able to set credentials sounds important enough that Microsoft would probably have fixed it already).

To reproduce:

public class Credentials : ICredentials
{
    public NetworkCredential GetCredential(Uri uri, string authType)
    {
        return new NetworkCredential("username", "password");
    }
}

public App()
{
    this.InitializeComponent();
    this.Suspending += OnSuspending;

    try
    {
        var credentials = new Credentials();
        var httpc = new HttpClientHandler();
        httpc.UseDefaultCredentials = false;
        httpc.Credentials = credentials;
    }
    catch (Exception ex)
    {
        return;
    }
}

The exception details are:

Message:

Value cannot be null.
Parameter name: format

StackTrace:

at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
at System.Net.Http.HttpClientHandler.set_Credentials(ICredentials value)
at WinTenTest.App..ctor()

I mean, it's clear what the internal problem is, but I have no idea why. The exception is thrown without GetCredential in the Credentials class is called, so it's not that.

The same code works perfectly in Windows 8.1 apps.

I'm using VS2015 RC, the latest W10 build and the latest dev tools, so I'm not out of date there either.

回答1:

As Yuval Itzchakov commented below the question, in this case you can just do

httpc.Credentials = new NetworkCredential("", "")

OR

httpc.Credentials = credentials.GetCredential(uri, authType).

I'm still intrigued as to why W10 has broken what worked in W8.1, but it's less important now.