Using HttpClient, how would I prevent automatic redirects and get original status code and forwading Url in the case of 301

Gga picture Gga · Feb 6, 2013 · Viewed 24.7k times · Source

I have the following method that returns the Http status code of a given 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);
}

It works well for 200/404 etc, however in the case of 301 codes I believe the returned result is the already-redirected (200) result, rather than the actual 301 that should be returned and which would have a header containing where the redirect would be pointed to.

I have seen something like this in other .Net web requests classes and the technique there was to set some sort of allowAutoRedirect property to false. If this is along the right lines, can anyone tell me the correct alternative for the HttpClient class?

This post has info on the above allowAutoRedirect concept I mean

Else, how might I get this method to return 301s rather than 200s for Urls I know to be genuine 301s?

Answer

Gga picture Gga · Feb 6, 2013

I have found that the way to do this is by creating an instance of HttpClientHandler and passing it in the constructor of 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))
        {

        }

See here for more info.