8

我正在考虑第一次使用 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 可能有多个请求同时出现错误。但发生这种情况的可能性很小。而且这个解决方案独立于会话,这在我们的例子中很重要,一些错误也可能导致会话终止等。因此,为什么这种方法对我们很有效。

4

1 回答 1

9

ErrorLogModuleELMAH(撰写本文时为 1.1 版)提供了一个Logged您可以处理的事件,您可以使用该事件Global.asax将详细信息(例如通过HttpContext.Items集合)传达给您的自定义错误页面。如果您ErrorLogModule在名称下注册了ErrorLogweb.config那么您的事件处理程序Global.asax将如下所示:

void ErrorLog_Logged(object sender, ErrorLoggedEventArgs args)  
{ 
    var id = args.Entry.Id
    // ...  
}
于 2010-02-05T23:37:38.640 回答