Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch connection errors for session state when it uses SQL to store session?

We have an ASP.NET application that uses SQL Server to store its session state. This works great except when it doesn't ;)

Our database servers are hosted by a 3rd party and they periodically perform maintenance on the SQL server. When this happens we want our code to gracefully detect db connection errors and display a friendly message that we are under maintenance. We wrote an HttpModule that runs with each request and instantiates an instance of our Entity Framework container. If the instantiation fails for any reason we know there are connection issues and we redirect the user to a maintenance page.

This works fine until we turn our session state server setting on. Session state accesses its connection string before this module is run. We then get an ugly connection error for session state.

How can we catch this error? Is there a place in our application where we can catch/detect session state connection errors and switch over to "in-process" session state?

like image 735
Chev Avatar asked Dec 28 '22 17:12

Chev


1 Answers

You should just be able to catch the error in the Application_Error method in Global.asax. Something like this will work, although you may want to make the check for if the exception is a Session related exception more robust. Unfortunately, ASP.NET doesn't throw a SessionException, just an HttpException that wraps a SqlException.

protected void Application_Error()
{
    Response.Clear();
    var ex = Server.GetLastError();
    if (ex is HttpException && 
        ex.Message.Contains("Unable to connect to SQL Server session database"))
    {
        Server.Transfer("/Maintenance.aspx");
    }
    else
    {
        Response.Write("Other error occurred.");
        Response.Write(ex.ToString());
        Response.End();
    }
}

In Maintenance.aspx make sure you set the EnableSessionState page directive to false. You can use a Server.Transfer to prevent the Session module from running again for this request and causing another exception to occur.

EDIT

Did a little testing, and it is probably better to use the following check to test if session is not working:

if (ex is HttpException && Context.Session == null)

Or possibly even just:

if (Context.Session == null)

Context.Session should always be null if the Session module fails (unfortunately I can't find any documentation to support that assertion, but in my testing that was the case).

like image 100
rsbarro Avatar answered Jan 11 '23 23:01

rsbarro