【发布时间】:2023-03-25 16:14:01
【问题描述】:
我在下载文件时遇到问题,该文件最终在 302 后返回。
假设我有一个这样的 URL:https://myhost/export/myfile.php。当我在浏览器中导航到此 URL 时,文件会下载。
但是,我想使用 C# 下载文件。
这是我尝试过的,使用HttpClient,但不起作用:
var uri = "https://myhost/export/myfile.php";
var requestMessage = new HttpRequestMessage(HttpMethod.Get, uri);
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
var response = await client.SendAsync(requestMessage);
if (response.IsSuccessStatusCode)
{
/// it never reach here because 302 is not sucess status code
}
}
我也尝试过使用WebClient:
var url = "https://myhost/export/myfile.php";
using (var webclient = new WebClient())
{
var response = await _webClient.DownloadDataTaskAsync(url); // throws an exception regarding HTTP status being 302 Found
string download = Encoding.ASCII.GetString(response);
}
如何下载重定向后返回的文件?
---------问题解决了------------ 在@Ermiya Eskandary 的支持下,我终于找到了根本原因。此请求缺少身份验证所需的标头名称“Cookie”(我用 cookie => 错误的请求配置误解了它)。感谢上帝派这个人来帮助我。
【问题讨论】:
-
var response = await _client.SendAsync(requestMessage);之后的状态码是什么 - 你100% 确定是 302 吗? -
您被重定向到的 URL 是什么?对于 .NET Core 1.0、1.1、2.0,它不会遵循从 HTTPS 到 HTTP 的重定向 - 请参阅 docs.microsoft.com/en-us/dotnet/api/…
-
是的,它是 302,我使用的是 netcore 3.1
标签: c# httpclient .net-core-3.1 http-status-code-302