C#: Get URL of HTTP Redirect

This is one of those snippets that might be useful someday:

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://this.domain.com/someThingThatRespondsWithRedirect");
webRequest.AllowAutoRedirect = false;
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
string redirectUrl = response.Headers.Get("Location"));

Typically browsers or the default http request class of your favorite programming language redirect you automatically in case they receive a HTTP Redirect status code. Typically that’s exactly what you want.
Last week however I ran into a situation in which I didn’t want the redirect to happen.
Since the code was written in VBScript / ASP, I first tried to accomplish it there. No chance. Good thing that I don’t have to rely entirely on VBScript. The C# WebRequest class has an attribute that allows to explicitly turn off the automatic redirect. You can read the Redirect-URL from the response header.

DeliciousTwitterFacebookLinkedInRedditSlashdotTechnorati FavoritesDiggShare
This entry was posted in C#. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">