asp.net - 如何在ASP.NET MVC中使用Application_Error?

标签 asp.net asp.net-mvc error-handling

我想在我的MVC项目中使用Application_Error,但是我无法使其正常工作。我将以下内容添加到我的Global.asax文件中:

    protected void Application_Error(object sender, EventArgs e)
    {
        Exception objErr = Server.GetLastError().GetBaseException();
        Session["Test"] = "Message:" + objErr.Message.ToString();
    }

(该 session 仅用于测试。如果我可以使用该数据库,我将使用数据库记录错误。)
然后,我尝试从HomeController和Home/Index View 中引发异常,但它只会触发Debug。
    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";
        throw (new Exception());
        return View();
    }

在我的Webconfig文件中,我设置了defaulterror页面,但它不会重定向到 View :
    <customErrors defaultRedirect="Home/Error">
        <error statusCode="403" redirect="NoAccess.htm" />
        <error statusCode="404" redirect="FileNotFound.htm" />
    </customErrors>

最佳答案

因此,首先请记住,全局错误处理应该是最后的选择,并且 Controller 类具有针对错误的特定错误方法;

protected virtual bool OnError(string actionName, 
    System.Reflection.MethodInfo methodInfo, Exception exception)

您可以在其中重定向到标准共享错误 View ;
protected override bool OnError(string actionName, 
    System.Reflection.MethodInfo methodInfo, Exception exception)
{
   RenderView("Error", exception);
   return false;
}

您在全局应用程序错误中遇到的问题是它没有 View 或 Controller 的概念,因此,如果要在其中进行重定向,则必须使用已知的URL
protected void Application_Error(object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();
    System.Diagnostics.Debug.WriteLine(exception);
    Response.Redirect("/Home/Error");
}

但您不需要这样做。如果您在web.config中设置默认错误页面,则不需要该重定向
<customErrors defaultRedirect="Home/Error" />

但是,除非您向Home Controller 添加了不存在的错误 View ,否则将以下内容添加到Home Controller
public ActionResult Error()
{
    return View();
}

然后(如果您很明智)将错误处理代码放在Error()方法中,因为这是所有未处理的错误将最终结束的地方。
public ActionResult Error()
{
    Exception exception = Server.GetLastError();
    System.Diagnostics.Debug.WriteLine(exception);
    return View();
}

最后要记住,默认情况下,如果您连接到本地主机,则不会看到自定义错误!所以你需要改变这种行为
<customErrors mode="On" defaultRedirect="/Home/Error" />

关于asp.net - 如何在ASP.NET MVC中使用Application_Error?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1464531/

相关文章:

c# - REST 服务错误响应负载是否应与媒体类型一致

python - 使用额外功能处理错误

c# - Microsoft 图表控件 - 每当我使用财务公式时,大红色 X(坏)

asp.net - 无法获取IIS提取目录

c# - 如何编写包含用户名的路由

vba - Vlookup 和 ISERROR

java - 错误: “The method is undefined for type” , and “The constructor is undefined”

asp.net - 在页面加载时将项目添加到列表框,并在单击按钮时将项目传输到另一个列表框

c# - 刚开始使用 Silverlight,我可以从主 Web 应用程序页面向我的嵌入式 silverlight "widget"发送数据吗?

javascript - Dust.js 逻辑助手的问题