【问题标题】:MVC 2 Catch-All for connection string missing or connect failureMVC 2 Catch-All 用于连接字符串丢失或连接失败
【发布时间】:2011-02-07 14:41:29
【问题描述】:

如果我的项目使用不正确、不完整或丢失的连接字符串部署,我希望应用程序启动检查数据库连接,如果没有,将所有请求定向到某种 DatabaseConnectionError 页面,什么是我的选择?我认为没有适合此错误的特定 http 错误代码,而且我目前没有使用 web.config 来定义所有错误的通用 catch all。

我有

    /// <summary>
    /// from http://www.davidjuth.com/asp-net-mvc-error-handler.aspx
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="args"></param>
    protected void Application_Error(object sender, EventArgs args)
    {
        Exception ex = Server.GetLastError();
        using (var crashFile = new System.IO.StreamWriter(Server.MapPath("~/App_Data/Crash_" + DateTime.UtcNow.ToString("yyyyMMdd") + ".log")))
            crashFile.WriteLine("<crash><time>" + DateTime.UtcNow.TimeOfDay.ToString() + "</time><url>" + HttpContext.Current.Request.Url + "</url><exception>" + ex.ToString() + "</exception></crash>");

    }

但它似乎不允许我用页面响应请求。

【问题讨论】:

    标签: asp.net-mvc error-handling connection-string database-connection web-config


    【解决方案1】:

    您可以在Application_Error 回调中重定向到自定义错误页面:

    protected void Application_Error(object sender, EventArgs args)
    {
        ...
        HttpApplication app = (HttpApplication)sender;
        HttpContext context = app.Context;
        context.Response.Redirect("~/error.html");
    }
    

    如果您不想重定向,也可以使用context.Server.Transfer 并设置一些特殊的http 错误代码,例如500。

    【讨论】:

      猜你喜欢
      • 2017-11-24
      • 2018-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 2015-06-02
      • 1970-01-01
      相关资源
      最近更新 更多