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.
-
Referencing
System.Weband usingHttpContext.Current.User.Identity.Nameworked like a charm. -
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().UserNameWhich way is quicker?
çağdaş : Considering User object is already populated in HttpContext, that should be quicker.changelog : Doesn't make a big difference, since this is a "mostly read" application. -
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();changelog : 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.
0 comments:
Post a Comment