【发布时间】:2013-01-27 03:53:46
【问题描述】:
我创建了一个错误页面来显示所有未处理异常的一般消息。
这是 Global.asax 中的代码
HttpContext ctx = HttpContext.Current;
string e404_PAGE = ctx.Request.AppRelativeCurrentExecutionFilePath.ToString();
string e404_LINE = ctx.Server.GetLastError().InnerException.StackTrace.Substring(ctx.Server.GetLastError().InnerException.StackTrace.LastIndexOf(":line ") + 6, ctx.Server.GetLastError().InnerException.StackTrace.Substring(ctx.Server.GetLastError().InnerException.StackTrace.LastIndexOf(":line ") + 6).IndexOf(" ")).ToString();
string e404_MESSAGE = ctx.Server.GetLastError().InnerException.Message.ToString();
string e404_METHODNAME = ctx.Server.GetLastError().InnerException.TargetSite.ToString();
string e404_STACKTRACE = ctx.Server.GetLastError().InnerException.StackTrace.ToString();
string e404_URL = ctx.Request.Url.ToString();
string e404_DATE = ctx.Timestamp.ToString("yyyy-MM-dd HH:mm:ss");
string e404_USER = ctx.User.Identity.Name.ToString();
string e404_IP = ctx.Request.UserHostAddress.ToString();
// * * * //
System.Data.SqlClient.SqlConnection sql_conn;
sql_conn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ToString());
sql_conn.Open();
string query = @"insert into UnhandledExceptions(Message, Page, Line, MethodName, StackTrace, URL, Date, [User], IP)
values(@Message, @Page, @Line, @MethodName, @StackTrace, @URL, @Date, @User, @IP)
select scope_identity();";
System.Data.SqlClient.SqlCommand com = new System.Data.SqlClient.SqlCommand(query, sql_conn);
com.Parameters.AddWithValue("@Message", e404_MESSAGE);
com.Parameters.AddWithValue("@Page", e404_PAGE);
com.Parameters.AddWithValue("@Line", e404_LINE);
com.Parameters.AddWithValue("@MethodName", e404_METHODNAME);
com.Parameters.AddWithValue("@StackTrace", e404_STACKTRACE);
com.Parameters.AddWithValue("@URL", e404_URL);
com.Parameters.AddWithValue("@Date", e404_DATE);
com.Parameters.AddWithValue("@User", e404_USER);
com.Parameters.AddWithValue("@IP", e404_IP);
string e404_ID = com.ExecuteScalar().ToString();
sql_conn.Close();
// * * * //
Session["e404_ID"] = e404_ID;
Response.Redirect("~/Error.aspx");
当我发布网站时,用户没有被重定向到错误页面。
直到最后一行的所有代码都可以正常工作。有什么建议吗?
【问题讨论】:
-
此代码在您的 Global.asax 中的什么位置?
-
@LuisTellez 代码在 Application_Error 中
-
只是指出显而易见的事情:您已经声明
Response.Redirect不起作用.. 但是您使用Server.Transfer。另外,您是否尝试过直接 URL? (没有波浪号) -
@SimonWhitehead 问题是我的应用程序中有文件夹和子文件夹,所以我需要一个 Error.aspx 页面的绝对路径,它位于根目录下。
-
你的
web.config中有customErrors属性吗?
标签: c# asp.net global-asax response.redirect