我正在123-Reg上托管一个网站,当前向用户显示错误消息-我已要求他们过去向我发送屏幕截图,以便我可以调试发生的情况。
但是,我想设置一个带有一些文本的自定义错误页面,然后将错误通过电子邮件发送到我的收件箱。但是,我在网上找到的任何内容似乎都建议对IIS进行更改。
由于我使用123-Reg托管,因此我无法访问IIS。可以在应用程序级别上实现吗?
最佳答案
在Global.asax页面上,只需添加以下代码
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
// Get the error details
HttpException lastErrorWrapper = Server.GetLastError() as HttpException;
Exception lastError = lastErrorWrapper;
if (lastErrorWrapper.InnerException != null)
lastError = lastErrorWrapper.InnerException;
string lastErrorTypeName = lastError.GetType().ToString();
string lastErrorMessage = lastError.Message;
string lastErrorStackTrace = lastError.StackTrace;
const string ToAddress = "youremail@yourdomain.com";
const string FromAddress = "noreply@yourdomain.com";
const string Subject = "An Error Has Occurred on Application Name!";
// Create the MailMessage object
MailMessage msg = new MailMessage();
string[] eAddresses = ToAddress.Split(';');
for (int i = 0; i < eAddresses.Length; i++)
{
if (eAddresses[i].Trim() != "")
{
msg.To.Add(new MailAddress(eAddresses[i]));
}
}
msg.From = (new MailAddress(FromAddress));
msg.Subject = Subject;
msg.IsBodyHtml = true;
msg.Priority = MailPriority.High;
msg.Body = string.Format(@"
<html>
<body>
<h1>An Error Has Occurred!</h1>
<table cellpadding=""5"" cellspacing=""0"" border=""1"">
<tr>
<td text-align: right;font-weight: bold"">URL:</td>
<td>{0}</td>
</tr>
<tr>
<td text-align: right;font-weight: bold"">User:</td>
<td>{1}</td>
</tr>
<tr>
<td text-align: right;font-weight: bold"">Exception Type:</td>
<td>{2}</td>
</tr>
<tr>
<td text-align: right;font-weight: bold"">Message:</td>
<td>{3}</td>
</tr>
<tr>
<td text-align: right;font-weight: bold"">Stack Trace:</td>
<td>{4}</td>
</tr>
</table>
</body>
</html>",
Request.Url,
Request.ServerVariables["LOGON_USER"],
lastErrorTypeName,
lastErrorMessage,
lastErrorStackTrace.Replace(Environment.NewLine, "<br />"));
// Attach the Yellow Screen of Death for this error
string YSODmarkup = lastErrorWrapper.GetHtmlErrorMessage();
if (!string.IsNullOrEmpty(YSODmarkup))
{
Attachment YSOD = Attachment.CreateAttachmentFromString(YSODmarkup, "YSOD.htm");
msg.Attachments.Add(YSOD);
}
// Send the email
SmtpClient smtp = new SmtpClient();
smtp.Send(msg);
Server.Transfer("/Error.aspx");
}
关于asp.net - 如何通过电子邮件向ASP.NET错误发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18321406/