Getting username inside model class
I am trying to implement basic auditing with some of my models (like CreatedAt, UpdAt, CreatedBy and UpdateBy).
Date / time in progress. I am throwing events on my models when a property changes (implementation INotifyPropertyChanging, INotifyPropertyChanged
) and can update the corresponding fields just fine.
I just need to know how to get the current username without having to pass it through the controller every time I create an instance or get an existing instance of the model.
0
source to share
3 answers
The abstract way of talking about personality is "main" - see this thread . I would like to hope that this code will allow you to get the identity without knowing about the login:
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();
+2
source to share