在 HttpClient 的多个重定向中传递授权标头



>我正在向服务器发送一个 get 请求,服务器重定向到 4 个 farthur 调用,然后返回响应。 HttpClient 给出异常,未提供授权令牌。

你能告诉我,如何在多个重定向上传递相同的授权令牌吗?如果我设置"AllowAutoRedirect=false"并返回RanToComplation Status,它可以正常工作。 这是我的方法:

static async Task CallWebAPIAsync()
{
WebRequestHandler webRequestHandler = new WebRequestHandler();
webRequestHandler.UseDefaultCredentials = true;
webRequestHandler.AllowPipelining = true;
webRequestHandler.AllowAutoRedirect = true;
using (var client = new HttpClient(webRequestHandler))
{
client.BaseAddress = new Uri("https://apirequest");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token);
client.Timeout = TimeSpan.FromSeconds(30000);
//GET Method  
var response = await client.GetAsync("user").ConfigureAwait(false); 
if (response.IsSuccessStatusCode)
{
var responseresult = await response.Content.ReadAsStringAsync();
Console.WriteLine("Id:{0}tName:{1}", responseresult);
}
else
{
Console.WriteLine("Internal server Error");
}
}

我认为问题可能与此有关

必须在重定向时剥离授权标头。我目前正在尝试弄清楚如何解决它。

我缺少将处理重定向的委派处理程序。 https://stackoverflow.com/a/19493338/3459965 此链接对我有帮助

更新的代码是:

static async Task CallWebAPIAsync()
{
HttpClientHandler clientHandler = new HttpClientHandler();
WebRequestHandler webRequestHandler = new WebRequestHandler();
webRequestHandler.UseDefaultCredentials = true;
webRequestHandler.AllowPipelining = true;
webRequestHandler.AllowAutoRedirect = false;
webRequestHandler.Credentials = CredentialCache.DefaultCredentials;

GlobalRedirectHandler globalRedirectHandler = new GlobalRedirectHandler() { InnerHandler = webRequestHandler };

using (var client = new HttpClient(globalRedirectHandler))
{
client.BaseAddress = new Uri("https://apitest");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token);

client.Timeout = TimeSpan.FromSeconds(30000);
//GET Method  
var response = await client.GetAsync("user").ConfigureAwait(false); 
if (response.IsSuccessStatusCode)
{
var responseresult = await response.Content.ReadAsStringAsync();
Console.WriteLine("Id:{0}tName:{1}", responseresult);
}
else
{
Console.WriteLine("Internal server Error");
}
}
}

相关内容

  • 没有找到相关文章

最新更新