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


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

I did not know about it. Thank you. I do it like this:



Membership.GetUser().UserName

      

Which way is faster?

+2


source


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


Link System.Web

and usage HttpContext.Current.User.Identity.Name

worked like a charm.

0


source







All Articles