Global.asax的使用方法

当页面遇到一个未处理的异常时,展现给用户的将是难看的报错信息。其实只要在Global.asax文件的Application_Error事件中添加用于处理异常的代码,就可以避免用户看到那些报错信息了。

例如

在WebForm1.cs的Page_Load事件中添加

using System.Text.RegularExpressions;

string errMessage = "遇到一个未处理的异常,请通知管理员,谢谢!";
  
if (Session["errMessage"] != null && int.Parse(Session["admin"]) != 0) // Session["admin"] = 1 表示浏览者是管理员
 errMessage = FormatError(Session["errMessage"].ToString());

Label1.Text = errMessage;

private string FormatError( string inputString )
{
 string temp = inputString;

 temp = Regex.Replace( temp, "/n", "<br>" );

 return temp;
}

在Global.asax的Application_Error事件中添加

 Exception lastError = Server.GetLastError();
 
 Session["errMessage"] = lastError.ToString();}

 Server.Transfer("error.aspx");

下面是具体介绍如何使用Global.asax的文章
使用ASP.NET Global.asax 文件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章