与自定义数据和事件侦听器的nhibernate会话

时间:2013-01-08 05:15:29

标签: wcf nhibernate auditing audit-trail

对于我正在研究的WCF项目,我需要为我们持久存在的实体实现某种审计日志。基本上审计跟踪将包含4个必填字段

  • CreatedDateTime
  • CreatedUserID
  • UpdatedDateTime
  • UpdatedUserID

我正在尝试通过我的DataAccess层中的nHibernate事件监听器来实现这一点,因为我认为这不应该在域层中。到目前为止,我已经按预期工作了DateTime,但是却无法弄清楚如何在事件监听器中检索userID。理想情况下,我希望将用户ID作为附加到nHibernate会话对象的某种自定义数据。

非常感谢任何建议。

2 个答案:

答案 0 :(得分:1)

.Net框架已经内置了对上下文用户身份信息的支持:Thread.CurrentPrincipal http://msdn.microsoft.com/en-us/library/system.threading.thread.currentprincipal.aspx

使用其中一个可用的IPrincipal实现或创建自己的实现 - 这很容易。然后在某些“开始请求”方法中尽早设置属性。

在ASP.NET代码中还要注意HttpContext.User。

答案 1 :(得分:1)

以下是我的工作方式,但我没有使用WCF做这方面的经验。请注意,这需要引用System.Web。

    /// <summary>
    ///   Returns the user name of the current user. Gets user name from HttpContext if running as a web app, else WindowsIdentity.
    /// </summary>
    private static string GetUserName()
    {
        var identity = HttpContext.Current == null ? WindowsIdentity.GetCurrent() : HttpContext.Current.User.Identity;
        if (identity == null)
        {
            throw new Exception("Identity could not be determined.");
        }
        // Remove domain name if present
        var s = identity.Name;
        var stop = s.IndexOf("\\", StringComparison.InvariantCultureIgnoreCase);
        return (stop > -1) ? s.Substring(stop + 1, s.Length - stop - 1).ToUpper() : s;
    }