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: }
5:
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