I need to get the url of the final destination of a shortened url. At the moment I am doing the following which seems to work:
var request = WebRequest.Create(shortenedUri);
var response = request.GetResponse();
return response.ResponseUri;
But can anyone suggest a better way?
You do need to make an HTTP request - but you don't need to follow the redirect, which WebRequest
will do by default. Here's a short example of making just one request:
using System;
using System.Net;
class Test
{
static void Main()
{
string url = "http://tinyurl.com/so-hints";
Console.WriteLine(LengthenUrl(url));
}
static string LengthenUrl(string url)
{
var request = WebRequest.CreateHttp(url);
request.AllowAutoRedirect = false;
using (var response = request.GetResponse())
{
var status = ((HttpWebResponse) response).StatusCode;
if (status == HttpStatusCode.Moved ||
status == HttpStatusCode.MovedPermanently)
{
return response.Headers["Location"];
}
// TODO: Work out a better exception
throw new Exception("No redirect required.");
}
}
}
Note that this means if the "lengthened" URL is itself a redirect, you won't get the "final" URI as you would in your original code. Likewise if the lengthened URL is invalid, you won't spot that - you'll just get the URL that you would have redirected to. Whether that's a good thing or not depends on your use case...