これがエラー メッセージをカスタム ページに渡す正しい方法である場合、この解決策についてどう思われますか?
web.config:
<customErrors mode="On" defaultRedirect="~/Error.aspx"></customErrors>
Global.asax で:
<script RunAt="server">
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
if (ex != null && Session != null)
{
ex.Data.Add("ErrorTime", DateTime.Now);
ex.Data.Add("ErrorSession", Session.SessionID);
HttpContext.Current.Cache["LastError"] = ex;
}
}
</script>
私のError.aspx.csで:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) return;
if (HttpContext.Current.Cache["LastError"] != null)
{
Exception ex = (Exception)HttpContext.Current.Cache["LastError"];
if (ex.Data["ErrorTime"] != null && ex.Data["ErrorSession"] != null)
if ((DateTime)ex.Data["ErrorTime"] > DateTime.Now.AddSeconds(-30d) && ex.Data["ErrorSession"].ToString() == Session.SessionID)
Label1.Text = ex.InnerException.Message;
}
}
問題: Global.asax から Server.Transfer を実行したくない.. わからない。私には不器用に見えました。customErrors を RemoteOnly に変更できるようにしたい。したがって、最後の例外をどこかに保存する必要がありますが、セッションにすることはできません。キャッシュに保存しますが、キャッシュはグローバルであり、誰かに間違ったエラーを表示しないようにするため、追加のデータ (時間とセッション ID) を付けて保存します。
コードを少し変更しました。今では次のとおりです。
void Application_Error(object sender, EventArgs e)
{
HttpContext.Current.Cache["LastError"] = Server.GetLastError().GetBaseException();
Server.ClearError();
}
...と...
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) return;
if (HttpContext.Current.Cache["LastError"] != null)
{
Exception ex = (Exception)HttpContext.Current.Cache["LastError"];
if (ex != null)
Label1.Text = ex.Message;
}
}
匿名ユーザーの場合、SessionID が存在しないことに注意してください。ex.Data.Add キーが既に存在するとエラーが発生し、ClearError を呼び出すことが重要であることがわかります。