42

我有以下方法返回Http status code给定的Url

public static async void makeRequest(int row, string url)
{
    string result;
    Stopwatch sw = new Stopwatch(); sw.Start();

    try
    {
        using (HttpClient client = new HttpClient())
        {
            HttpResponseMessage response = new HttpResponseMessage();
            response = await client.GetAsync(url);

            // dump contents of header
            Console.WriteLine(response.Headers.ToString());

            if (response.IsSuccessStatusCode)
            {
                result = ((int)response.StatusCode).ToString();
            }
            else
            {
                result = ((int)response.StatusCode).ToString();
            }
        }
    }
    catch (HttpRequestException hre)
    {
        result = "Server unreachable";
    }

    sw.Stop();
    long time = sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L));

    requestComplete(row, url, result, time);
}

它适用于200/404等,但是在301代码的情况下,我相信返回的结果是已经重定向的( 200) 结果,而不是301应该返回的实际结果,并且它会有一个包含重定向指向的标头。

我在其他 .Net Web 请求类中看到过类似的情况,并且将某种allowAutoRedirect属性设置为 false 的技术。如果这是正确的路线,任何人都可以告诉我该HttpClient课程的正确替代方案吗?

这篇文章有关于上述 allowAutoRedirect 概念的信息,我的意思是

否则,我怎样才能让这个方法返回301s而不是200s让我知道是真实的 Urls 301s

4

1 回答 1

75

我发现做到这一点的方法是创建一个实例HttpClientHandler并将其传递给HttpClient

public static async void makeRequest(int row, string url)
{
    string result;
    Stopwatch sw = new Stopwatch(); sw.Start();

    // added here
    HttpClientHandler httpClientHandler = new HttpClientHandler();
    httpClientHandler.AllowAutoRedirect = false;

    try
    {
        // passed in here
        using (HttpClient client = new HttpClient(httpClientHandler))
        {

        }

请参阅此处了解更多信息。

于 2013-02-06T15:16:24.890 回答