在 .Net Core 3.1 应用程序中使用 Mongo Atlas API,但我无法获得 HttpClient
处理来自摘要式身份验证的挑战。
该代码发送第一个请求,获得 401 响应,然后不通过正确的身份验证重新发送。
下面是我一直在努力工作的代码
var domain = "https://cloud.mongodb.com/";
var credCache = new CredentialCache();
credCache.Add(new Uri(domain),"Digest", new NetworkCredential(user,secret));
var httpClient = new HttpClient( new HttpClientHandler { Credentials = credCache});
var answer = await httpClient.GetAsync(new Uri($"{domain}api/atlas/v1.0/groups/{groupId}/databaseUsers"));
这是我得到的回应
StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Date: Mon, 27 Jan 2020 21:03:14 GMT
WWW-Authenticate: Digest realm="MMS Public API", domain="", nonce="generatedNonce", algorithm=MD5, qop="auth", stale=false
Content-Type: application/json
Content-Length: 106
}
我已经成功发送了 curl 请求,所以我确定我的用户/ secret /组是正确的。
有没有人看到该代码有问题,或者知道我可以做些什么来进一步调试这个问题?
最佳答案
显然我们遇到了完全相同的问题,或者至少在我的同事找到解决方案之前我遇到过。
2.1 中的 HttpClient 内部有很多变化以支持新的 SocketsHttpHandler,使用这行代码回到 2.0 功能,它应该可以再次工作,把它Main
或在您调用电话之前的某个地方。
AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);
否则,您必须先发送一个请求才能获得
401
回复抢nonce
来自 WwwAuthenticate
标题,您可能还需要在标题中设置更多字段。干杯!
在 reddit 上的这篇文章中找到它:https://www.reddit.com/r/dotnet/comments/9yailz/weird_dotnet_core_httpclient_bug_maybe/ea07edd/
关于c# - .Net Core HttpClient 摘要身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59939357/