Question

For a WCF project I'm working on, I need to implement some kind of audit log for the entities we're persisting. Basically the audit trail will consist of 4 mandatory fields

  • CreatedDateTime
  • CreatedUserID
  • UpdatedDateTime
  • UpdatedUserID

I'm trying to implement this through nHibernate Event Listeners in my DataAccess layer as I think this should not be in the domain layer. So far, I've got the DateTime stuff working as expected, but haven't been able to figure out how to retrieve the userID in the event listener. Ideally, I would like to have the user id as some sort of custom data attached to the nHibernate session object.

Any suggestion is greatly appreciated.

Was it helpful?

Solution

The .Net framework already has builtin support for contextual user identity information: Thread.CurrentPrincipal http://msdn.microsoft.com/en-us/library/system.threading.thread.currentprincipal.aspx

Use one of the available IPrincipal implementations or create your own - it's easy. Then set the property early on, in some "begin-request" method.

There is also HttpContext.User to be aware of in ASP.NET code.

OTHER TIPS

Here's how I'm doing it but I don't have experience doing this with WCF. Note that this requires a reference to 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;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top