我是 ASP.NET 的新手,我有一个非常基本的站点,我只想获取所有应用程序错误并将它们通过电子邮件发送给我,同时为用户提供一个错误页面。我阅读了很多关于这个主题的内容,似乎有很多信息。以下是我想出的,但我在保持会话中的异常时遇到问题,因此我可以通过电子邮件将其发送给我。
我不断NullReferenceException was unhandled by user code
从 Error.aspx.cs 文件中获得关于 ex.Message 的信息。
有什么想法吗?
Global.asax.cs-
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
HttpContext.Current.Response.Redirect("~/Error.aspx");
}
错误.aspx.cs-
public partial class Error : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Exception ex = (Exception)Session["Exception"];
this.SendEmail(ex);
Session.Remove("Exception");
}
}
private void SendEmail(Exception ex)
{
string body = "An exception occured at "
+ DateTime.Now.ToLongTimeString()
+ " on " + DateTime.Now.ToLongDateString()
+ "<br />" + ex.Message; //ERROR HERE
MailMessage msg = new MailMessage("from@email.com", "to@email.com");
msg.Subject = "Exception in Portal Website";
msg.Body = body;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("localhost");
client.Send(msg);
}
}