views:

99

answers:

3

I'm trying to implement basic auditing with some of my models (like CreatedAt, UpdatedAt, CreatedBy and UpdatedBy).

The date/time part is done. I'm throwing events on my models when a property is changed (implementing INotifyPropertyChanging, INotifyPropertyChanged) and can update the correspondent fields just fine.

I just need to know how to get the current user name without having to pass it through the controller every time I instantiate or get an existing instance of a model.

A: 

Referencing System.Web and using HttpContext.Current.User.Identity.Name worked like a charm.

changelog
+2  A: 

Hi!

Referencing System.Web and using HttpContext.Current.User.Identity.Name worked like a charm.

I didn't know about it. Thanks. I do it like this:

Membership.GetUser().UserName

Which way is quicker?

Dmitry44
Considering User object is already populated in HttpContext, that should be quicker.
çağdaş
Doesn't make a big difference, since this is a "mostly read" application.
changelog
+2  A: 

The abstract way of talking about identity is the "principal" - see this thread. I would hope that this code allows you to get the identity without having to know about the login implementation:

public static class SomeUtilityClass {
    public static string GetUsername() {
        IPrincipal principal = Thread.CurrentPrincipal;
        IIdentity identity = principal == null ? null : principal.Identity;
        return identity == null ? null : identity.Name;
    }
}
...

record.UpdatedBy = record.CreatedBy = SomeUtilityClass.GetUsername();
Marc Gravell
I don't want to keep specifying it, so it works better with a subscription to the event and doing it on the model itself. Thanks for the reference tho.
changelog