Asp.net-Mvc
ELMAH - 使用自定義錯誤頁面收集使用者回饋
我正在考慮第一次使用 ELMAH,但有一個需要滿足的要求,我不確定如何實現……
基本上,我將配置 ELMAH 使其在 asp.net MVC 下工作,並讓它在發生錯誤時將錯誤記錄到數據庫中。最重要的是,當發生錯誤時,我使用 customErrors 將使用者引導到友好的消息頁面。相當標準的東西…
要求是在這個自定義錯誤頁面上,我有一個表單,如果他們願意,使用者可以提供額外的資訊。現在問題出現了,因為此時錯誤已被記錄,我需要將記錄的錯誤與使用者回饋相關聯。
通常,如果我使用自己的自定義實現,在記錄錯誤後,我會將錯誤的 ID 傳遞到自定義錯誤頁面,以便建立關聯。但由於 ELMAH 的工作方式,我認為不太可能。
因此,我想知道人們如何認為一個人可能會這樣做……
乾杯
更新:
我對這個問題的解決方案如下:
public class UserCurrentConextUsingWebContext : IUserCurrentConext { private const string _StoredExceptionName = "System.StoredException."; private const string _StoredExceptionIdName = "System.StoredExceptionId."; public virtual string UniqueAddress { get { return HttpContext.Current.Request.UserHostAddress; } } public Exception StoredException { get { return HttpContext.Current.Application[_StoredExceptionName + this.UniqueAddress] as Exception; } set { HttpContext.Current.Application[_StoredExceptionName + this.UniqueAddress] = value; } } public string StoredExceptionId { get { return HttpContext.Current.Application[_StoredExceptionIdName + this.UniqueAddress] as string; } set { HttpContext.Current.Application[_StoredExceptionIdName + this.UniqueAddress] = value; } } }然後當錯誤發生時,我的 Global.asax 中有這樣的內容:
public void ErrorLog_Logged(object sender, ErrorLoggedEventArgs args) { var item = new UserCurrentConextUsingWebContext(); item.StoredException = args.Entry.Error.Exception; item.StoredExceptionId = args.Entry.Id; }然後無論您以後在哪裡,您都可以通過以下方式提取詳細資訊
var item = new UserCurrentConextUsingWebContext(); var error = item.StoredException; var errorId = item.StoredExceptionId; item.StoredException = null; item.StoredExceptionId = null;請注意,這並不是 100% 完美的,因為同一 IP 可能有多個請求同時出現錯誤。但發生這種情況的可能性很小。而且這個解決方案獨立於會話,這在我們的例子中很重要,一些錯誤也可能導致會話終止等。因此,為什麼這種方法對我們很有效。
ErrorLogModuleELMAH(撰寫本文時為 1.1 版)提供了一個您可以在其中Logged處理的事件,您可以使用該事件Global.asax將詳細資訊(例如通過HttpContext.Items集合)傳達給您的自定義錯誤頁面。如果您ErrorLogModule在名稱下註冊了ErrorLog,web.config那麼您的事件處理程序Global.asax將如下所示:void ErrorLog_Logged(object sender, ErrorLoggedEventArgs args) { var id = args.Entry.Id // ... }