Reputation: 4681
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.
Upvotes: 0
Views: 1223
Reputation: 1063328
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();
Upvotes: 2
Reputation: 841
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?
Upvotes: 2
Reputation: 4681
Referencing System.Web
and using HttpContext.Current.User.Identity.Name
worked like a charm.
Upvotes: 1