I am trying to get the URL of a page using HttpClient. I've previously only used HttpWebRequest, but I need to make this an async method. In the code below, myUri always returns null which results in throwing an exception when I try to handle it later on.
Is the location header the wrong thing to be using?
        string myUrl = "http://www.example.com/"; 
        Uri myUri= new Uri(myUrl);
        using (HttpClient client = new HttpClient())
        using (HttpResponseMessage response = await client.GetAsync(myUri))
        {
            if (response.IsSuccessStatusCode)
            {
                myUri= response.Headers.Location;
                Debug.WriteLine("True "+ myUri);
            } 
            else {
                Debug.WriteLine("False " + myUri);
            }
        }
It's because HttpClient will automatically follows redirects. If you need the URL a page redirects to, you need to stop it from automatically following:
Change your code to the following:
string myUrl = "http://www.example.com/"; 
Uri myUri= new Uri(myUrl);
HttpClientHandler httpClientHandler = new HttpClientHandler();
httpClientHandler.AllowAutoRedirect = false;
using (HttpClient client = new HttpClient(httpClientHandler))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With