1

If you look at the answer on this page, you can see its outdated code. How to upgrade it to HttpClient and using async methods instead?

I have been trying to adapt this code for a number of hours now and all I get are errors.

First of all, I cannot return a StringBuilder object with the depth of all strings, Status Codes and Status Messages. One at a time would be fine adding a new line to it.

public async Task ExpandedURLsAsync(string url)  
{
    string location = url;
    string strTemp = location;

    while (!string.IsNullOrWhiteSpace(location)) 
    {
        strTemp += location + Environment.NewLine;

        using HttpClientHandler handler = new() 
        {
            AllowAutoRedirect = false
        };

        using HttpClient client = new(handler);
        client.DefaultRequestHeaders.Add("HTTP_USER_AGENT", "Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64;+rv:101.0)+Gecko/20100101+Firefox/101.0");

        using HttpResponseMessage response = await client.GetAsync(location);

        if (!string.IsNullOrEmpty(response.Headers.Location.ToString())) 
        {
            location = response.Headers.Location.ToString();
            strTemp += location + ", " + response.StatusCode + ", " + Environment.NewLine;
        }
    }
}

And how to use while in a loop to get every level of the redirect? If I say:

AllowAutoRedirect = true

then I receive nothing but the final redirected link.

I saw on another site, you can do a level redirect upto 50 levels but 3 or 4 will be enough.

I still think AllowAutoRedirect = false is the way to go. And in the code shown above, GetAsync location can be a url but the line under maybe null. Change both to location and there is a loop of the final link.

What I tried and what am I expecting are written above

2
  • 1
    I'm guessing then that when response.Headers.Location is null, you're getting an exception when you call .ToString() on it? Commented Jul 11, 2024 at 2:07
  • 2
    Also, create one HttpClient. Each time you dispose it, you are dropping the ssl connections to all servers, which you need to recreate for each request. Commented Jul 11, 2024 at 4:59

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.