C# 301使用AllowAutoRedirect永久移动

C# 301使用AllowAutoRedirect永久移动,c#,.net,networking,C#,.net,Networking,我编写了一个从站点获取html的类,代码如下: public class NetworkHelper { static Lazy<HttpClient> httpClient = new Lazy<HttpClient>(() => { var handler = CreateHandler(); return new HttpClient(handler) { Timeout = TimeSpan.F

我编写了一个从站点获取html的类,代码如下:

public class NetworkHelper {
    static Lazy<HttpClient> httpClient = new Lazy<HttpClient>(() => {
        var handler = CreateHandler();
        return new HttpClient(handler) {
            Timeout = TimeSpan.FromSeconds(3)
        };
    });

    static HttpMessageHandler CreateHandler() {
        var handler = new HttpClientHandler();
        // if the framework supports redirect configuration
        // set max redirect to the desired amount the default is 50
        if (handler.SupportsRedirectConfiguration) {
            handler.AllowAutoRedirect = true;
            handler.MaxAutomaticRedirections = 5;
        }
        // if the framework supports automatic decompression 
        // set automatic decompression
        if (handler.SupportsAutomaticDecompression) {
            handler.AutomaticDecompression = System.Net.DecompressionMethods.GZip |
                System.Net.DecompressionMethods.Deflate;
        }
        return handler;
    }

    /// <summary>
    /// Get the html structure of a site.
    /// </summary>
    /// <param name="url">Represents the URL of the page where to download the data.</param>
    /// <returns>Return a string that contains the html of the site.</returns>
    public async Task<string> GetHtmlAsync(Uri url, CancellationToken cancellationToken = default(CancellationToken)) {
        var response = await httpClient.Value.GetAsync(url, cancellationToken);
        var content = await response.Content.ReadAsStringAsync();
        return content;
    }
}
我将获得以下内容:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>301 Moved Permanently</title>
</head><body>
<h1>Moved Permanently</h1>
<p>The document has moved <a href="http://int.soccerway.com/charts/statsplus/2139109/">here</a>.</p>
</body></html>

301永久搬迁
永久移除
文档已移动


所以我猜
AllowAutoRedirect
没有按预期工作?

我发现改变:

return new HttpClient(handler) {
        Timeout = TimeSpan.FromSeconds(3)
    };
致:


一切都很好。似乎每秒可以执行的HTTP请求数量有限,其他请求会排队。

GetHtmlAsync将Uri作为参数,而不是字符串。你确定你发布了正确的代码吗?@Eser是的,我修复了这个示例。我不明白为什么它不起作用(我更喜欢在类范围内使用
NetworkHelper NetHelper=new NetworkHelper();
声明,因为你使用的是静态对象初始值设定项,但在这里它不会改变结果)。你的目标是什么?(请注意,
Timeout
MaxAutomaticRedirections
远低于默认值)@Jimi我使用的是
.NET Standard 2.0
你试过了吗?我现在没有可用的IDE。我所知道的是,如果重定向将连接从Https移动到Http,则.NET Core不允许自动重定向,无论
AllowAutoRedirect
怎么说。我不确定这是否也适用于.Net标准。我会在可能的时候测试它。您也可以这样做(可能使用.Net framerwork 4.6.1+)。我建议为<代码>超时和 Max AutoToCurrest<<代码>设置更高的值。然后考虑增加超时时间跨度。
return new HttpClient(handler) {
        Timeout = TimeSpan.FromSeconds(3)
    };
return new HttpClient(handler) {
            //Timeout = TimeSpan.FromSeconds(3)
        };