Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get URL using HttpClient C# .NET

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);
            }
        }
like image 566
Sam B Avatar asked Oct 29 '25 01:10

Sam B


1 Answers

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))
like image 104
Rob Avatar answered Oct 30 '25 16:10

Rob