Petar Slavov
Petar Slavov

Reputation: 176

Findout where does an url redirects in C#

I have an url of the type http://somesite.com/photo/123 that redirects to an url somesite.com/13sjd_9488.jpg. How can I go from the first url to the second one in .NET and Silverlight?

Upvotes: 0

Views: 276

Answers (2)

Ani
Ani

Reputation: 113402

If you can send an HttpRequest:

public static bool TryGetRedirectedUri(Uri uri, out Uri redirectedUri)
{
    var request = (HttpWebRequest)WebRequest.Create(uri);
    request.AllowAutoRedirect = false;
    using (var response = (HttpWebResponse)request.GetResponse())
    {
        if (response.StatusCode == HttpStatusCode.Moved)
        {
            redirectedUri = new Uri(response.Headers[HttpResponseHeader.Location]);
            return true;
        }

        else
        {
            redirectedUri = null;
            return false;
        }
    }
}

Note: This doesn't cover all cases, and needs more sanity checks.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

You can't do this at the client side because this redirection is done on the server side, so unless you send an HTTP request to this url you cannot do it:

var request = WebRequest.Create("http://somesite.com/photo/123");
request.BeginGetResponse(ar => 
{
    using (var response = ((WebRequest)ar.AsyncState).EndGetResponse(ar))
    {
        // This will point to the redirected url: 
        // http://somesite.com/13sjd_9488.jpg
        string responseUri = response.ResponseUri.AbsoluteUri;
    }
}, request);

Upvotes: 1

Related Questions