ASP.NET MVC: Check database connectivity on application startup

江枫思渺然 提交于 2020-01-02 18:52:09

问题


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());


来源:https://stackoverflow.com/questions/37098772/asp-net-mvc-check-database-connectivity-on-application-startup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!