Search code examples
sqlasp.netmaintenance-mode

Disable (Politely) a website when the sql server is offline


I work at a college and have been developing an ASP.NET site with many, many reports about students, attendance stats... The basis for the data is an MSSQL server DB which is the back end to our student management system. This has a regular maintenance period on Thursday mornings for an unknown length of time (dependent on what has to be done).

Most of the staff are aware of this but the less regular users seem to be forever ringing me up. What is the easiest way to disable the site during maintenance obviously I can just try a DB query to test if it is up but am unsure of the best way to for instance redirect all users to a "The website is down for maintenance" message, bearing in mind they could have started a session prior to the website going down.

Hopefully, something can be implemented globally rather than per page.


Solution

  • I would suggest doing it in Application_PreRequestHandlerExecute instead of after an error occurs. Generally, it'd be best not to enter normal processing if you know your database isn't available. I typically use something like below

    void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
    {
     string sPage = Request.ServerVariables["SCRIPT_NAME"];
     if (!sPage.EndsWith("Maintenance.aspx", StringComparison.OrdinalIgnoreCase))
     {
      //test the database connection
      //if it fails then redirect the user to Maintenance.aspx
      string connStr = ConfigurationManager.ConnectionString["ConnectionString"].ConnectionString;
      SqlConnection conn = new SqlConnection(connStr);
      try
      {
       conn.Open();
      }
      catch(Exception ex)
      {
       Session["DBException"] = ex;
       Response.Redirect("Maintenance.aspx");
      }
      finally
      {
       conn.Close();
      }
     }
    }