ASP.NET MVC:在应用程序启动时检查数据库连接 [英] ASP.NET MVC: Check database connectivity on application startup

查看:101
本文介绍了ASP.NET MVC:在应用程序启动时检查数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1-有时我的SQL Server出于维护目的而关闭,因此当我尝试运行ASP.NET MVC应用程序时,我会遇到带有错误network-related or instance-specific error occurred while establishing a connection to SQL Server.

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.

由于我不知道ASP.NET MVC中的事件顺序,所以我想知道应该在哪里检查连接性,以便可以将用户重定向到通知他/她有关这种情况的视图(而不是显示此错误页面) . 我看到了此答案在asp.net论坛中,但是我不明白如何在global.asax内部处理该问题.

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-是否可以进行一些更改,对于每个数据库连接错误,我都可以将用户重定向到该信息页面?我的意思是可以为数据库连接错误定义全局异常处理程序吗?

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?

PS .我在web.config中的connectionString名为DefaultConnection.

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

推荐答案

我认为您可以准备一个全局过滤器(如果您有很多控制器并且不想用一个属性来装饰每个控制器),并仅使用它来检查一下引发了某种异常,例如将用户重定向到一些自定义视图:

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

然后只需在Application_Start()方法中的Global.asax中注册它即可:

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

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

这篇关于ASP.NET MVC:在应用程序启动时检查数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆