Question

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.

Was it helpful?

Solution

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?

OTHER TIPS

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();

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top