使用HttpClient,如何防止自动重定向并获取原始状态代码并在301的情况下转发Url

时间:2013-02-06 14:55:07

标签: c# http redirect httpclient

我有以下方法返回给定Http status code的{​​{1}}:

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代码,我认为返回的结果是已经重定向({ {1}})结果,而不是应返回的实际301,以及包含重定向指向位置的标题。

我在其他.Net Web请求类中看到过类似的内容,并且将某种200属性设置为false。如果这是沿着正确的路线,有人能告诉我301类的正确选择吗?

This post has info on the above allowAutoRedirect concept I mean

否则,我怎么能让这个方法返回allowAutoRedirect而不是HttpClient我知道真正的301s的网址?

1 个答案:

答案 0 :(得分:50)

我发现这样做的方法是创建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))
        {

        }

有关详细信息,请参阅here