ASP.NET MVC: Check database connectivity on applic

2019-05-18 20:53发布

问题:

1- Sometimes my SQL Server is down for maintenance, so when I try to run my ASP.NET MVC application i face the yellow error screen with error network-related or instance-specific error occurred while establishing a connection to SQL Server.

Since I don't know the sequence of events in ASP.NET MVC I want to know where I should check connectivity so can I redirect user to a view informing him/her about this situation (instead of displaying this error page). I saw this answer in asp.net forum but I couldn't understand how can I handle this inside global.asax.

2- Is it possible to do some changes which for every database connection error I can redirect user to that information page? I mean is it possible to define global exception handler for database connection error?

P.S. My connectionString in web.config is named DefaultConnection.

回答1:

I think you can prepare a global filter(if you have many controllers and don't want to decorate each with an attribute) and just use it to check what kind of exception has been thrown and e.g. redirect user to some custom view:

public class SqlExceptionFilter: IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        // Do your logic
    }
}

And then just register it in Global.asax in Application_Start() method:

GlobalFilters.Filters.Add(new SqlExceptionFilter());