我如何在ASP.NET MVC中使用Application_Error?

我想使用Application_Error与我的MVC项目,但我不能让它上班.我将以下内容添加到我的Global.asax文件中:
protected void Application_Error(object sender,EventArgs e)
    {
        Exception objErr = Server.GetLastError().GetBaseException();
        Session["Test"] = "Message:" + objErr.Message.ToString();
    }

(会话仅用于测试,如果我得到这个工作,我将使用数据库记录错误.)
然后我尝试从我的HomeController和我的Home / Index View抛出一个异常,但它只会触发Debug.

public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";
        throw (new Exception());
        return View();
    }

在我的Webconfig文件中,我设置了一个defaulterror页面,但它不会重定向到视图:

<customErrors defaultRedirect="Home/Error">
        <error statusCode="403" redirect="NoAccess.htm" />
        <error statusCode="404" redirect="FileNotFound.htm" />
    </customErrors>

解决方法

所以首先要记住,全局错误处理应该是最后的手段,控制器类对错误一个特定的错误方法;
protected virtual bool OnError(string actionName,System.Reflection.MethodInfo methodInfo,Exception exception)

在此您可以重定向到标准共享错误视图;

protected override bool OnError(string actionName,Exception exception)
{
   RenderView("Error",exception);
   return false;
}

您在全局应用程序错误中遇到的问题是它没有视图或控制器的概念,因此如果要在其中重定向,则必须使用已知的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控制器添加了不存在的错误视图,否则将以下内容添加到主控制器

public ActionResult Error()
{
    return View();
}

然后(如果你是明智的),你可以将错误处理代码放在Error()方法中,因为所有未处理的错误都将结束.

public ActionResult Error()
{
    Exception exception = Server.GetLastError();
    System.Diagnostics.Debug.WriteLine(exception);
    return View();
}

最后记住,如果您连接到localhost,认情况下不会看到自定义错误!所以你需要改变这种行为

<customErrors mode="On" defaultRedirect="/Home/Error" />

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....