Safe Redirect (302 Found)

I’ve just came across a question what to do if the url I wants to redirect to is invalid (server is down etc.). Obviously the redirect will fail but that is exactly what I would like to avoid. The solution is dead simple and can look like that:

   1: protected void Page_Load(object sender, EventArgs e)
   2: {
   3:     TryRedirect(TextBox1.Text);
   4: }
   6: private void TryRedirect(string url)
   7: {
   8:     ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
   9:     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  10:     try
  11:     {
  12:         using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
  13:         {
  14:             if (response.StatusCode == HttpStatusCode.OK)
  15:             {
  16:                 Response.Redirect(url, true);
  17:             }
  18:         }
  19:     }
  20:     catch (Exception ex)
  21:     {
  22:     }
  23:     Response.Redirect("Recovery.aspx?url=" + HttpUtility.UrlEncode(url), true);
  24: }

Of course much more can be done here. One can store recovery url in config file or have it dynamic depend on some criteria such customer name. Each failed redirection can be logged and/or reported somewhere etc. But the idea is dead simple.

Posted 09-17-2009 5:33 PM by Jimmy
Filed under: ,


About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Google Reader or Homepage Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of
Red-Gate Tools For SQL and .NET


SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
NHibernate Profiler
Balsamiq Mockups
JetBrains - ReSharper
Web Sequence Diagrams
Ducksboard<-- NEW Friend!


Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers


Community Server (Commercial Edition)