11.在Global的Application_Error处理错误示例

Application_Error是在程序出问题时触发的事件。

这里面要用到错误页的情况,所以要配置web.config的customError项。

1.建立Global文件,在它的Application_Error中写入以下代码(TextFile1.txt 是要记录出错信息的日志):

 protected void Application_Error(object sender, EventArgs e)
        {
            Exception ex = HttpContext.Current.Server.GetLastError();
            File.WriteAllText(HttpContext.Current.Server.MapPath("~/TextFile1.txt"), ex.Message + DateTime.Now.ToShortTimeString());
        }

2.建立两个错误页,一个为默认的错误页,另一个为404状态的错误页,即页面没有被找到,

   默认错误页error.htm

  

复制代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
出错啦
</body>
</html>
复制代码

 找不到文件错误页NotFoundFile.htm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> 没找到相关文件 </body> </html>

3.设置web.config,具体说明可以看错误页章节

  

复制代码
<?xml version="1.0" encoding="utf-8"?>

<!--
  有关如何配置 ASP.NET 应用程序的详细消息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
      <customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="error.htm">
        <error statusCode="404" redirect="NotFoundFile.htm"/>
      </customErrors>
    </system.web>

</configuration>
复制代码

4.建立一个webform面,在它的page_load事件中写如下cs代码:

 protected void Page_Load(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection("IP:127.0.0.1;datasource=db1.db");
            conn.Open();
        }

此时运行时就会显示错误页,打开TextFile1.txt后会出现日志已记录在文件中,如下图日志记录

posted on   天上星  阅读(2982)  评论(0编辑  收藏  举报

编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示