首页 > 解决方案 > AllowAutoRedirect 设置为 true 的 HttpClient 不起作用

问题描述

在 .NET Core 3.1 Web 应用程序中,我尝试使用HttpClient处理程序将用户重定向到网站并传递凭据:

string url = "https://somewebsite.com/";

var handler = new HttpClientHandler
{
    AllowAutoRedirect = true,
    Credentials = new NetworkCredential("username", "password", "domain"),
};

var client = new HttpClient(handler);
var headerResponse = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);

Debug.WriteLine("Response: " + headerResponse.StatusCode);

foreach (var item in headerResponse.Headers)
{
    Debug.WriteLine($"Header: {item.Key} - {string.Join(",", item.Value)}");
}

文档说如果AllowAutoRedirect设置为 true ,则应该在client.GetAsync调用之后进行重定向。就我而言,我永远不会被重定向。我正在阅读 http 网站不会重定向到 https ,反之亦然。我尝试了 http 和 https 链接,但从未发生过重定向。这是我正在查看的一个示例:https ://www.conradakunga.com/blog/http-redirects-using-httpclient/ 。我注意到我的响应标头总是缺少“位置”项。

这是我得到的回复:

响应:好的
标题:日期 - 格林威治标准时间 2021 年 10 月 22 日星期五 18:19:34
标题:传输编码 - 分块
标题:连接 - 保持活动
标题:服务器 - nginx
标题:缓存控制 - 无缓存,私有
标题: X-Frame-Options - SAMEORIGIN,SAMEORIGIN
标头:Set-Cookie - XSRF-TOKEN=blablablabla;最大年龄=7200;路径=/; httponly
标头:X-XSS-Protection - 1;mode=block
标头:X-Content-Type-Options - nosniff

知道我做错了什么吗?谢谢

标签: c#redirect.net-corehttpclientcredentials

解决方案


推荐阅读