HttpClient的使用在Windows商店应用摘要式身份验证(C#)(Digest authen

2019-10-23 02:58发布

我这个问题了一个星期挣扎。 我必须使用API​​在Windows Store应用摘要式身份验证,但是当我使用这个代码,我在这行代码得到System.ArgumentNullException:

HttpHandler.Credentials = credCache;

下面是代码其余部分:

var credCache = new CredentialCache();
credCache.Add(new Uri("https://myserverIP/api"),"Digest",new NetworkCredential("mylogin", "mypassword") );
var HttpHandler = new HttpClientHandler();
HttpHandler.Credentials = credCache;
var httpClient = new HttpClient(HttpHandler);
var answer = await httpClient.GetAsync(new Uri("https://myserverIP/api/?function=someKindOfFunction"));
answer.EnsureSuccessStatusCode();

我究竟做错了什么?

Answer 1:

快速解决您的问题是使用credCache.GetCredentials()而不是仅仅credCache值分配给HttpHandler的时候。 凭据,如:

var credCache = new CredentialCache();
credCache.Add(new Uri("https://myserverIP/api"),"Digest",new NetworkCredential("mylogin", "mypassword") );
var HttpHandler = new HttpClientHandler();
HttpHandler.Credentials = credCache.GetCredential(new Uri("https://myserverIP/api"), "Digest");

此作品,未经ArgumentNullException

希望这可以帮助。

谢谢,希德



文章来源: Digest authentication in Windows Store app using HttpClient (C#)