Hello,
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?
Hello,
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?
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);
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.