代码之家  ›  专栏  ›  技术社区  ›  changelog

在模型类中获取用户名

  •  0
  • changelog  · 技术社区  · 16 年前

    我试图用我的一些模型(比如CreatedAt、UpdatedAt、CreatedBy和UpdatedBy)实现基本审计。

    完成日期/时间部分。当属性更改(实现)时,我在模型上抛出事件 INotifyPropertyChanging, INotifyPropertyChanged

    我只需要知道如何获取当前用户名,而不必在每次实例化或获取模型的现有实例时将其传递给控制器。

    3 回复  |  直到 16 年前
        1
  •  2
  •   Dmitry44    16 年前

    参考System.Web并使用 HttpContext.Current.User.Identity.Name 工作得很有魅力。

    我不知道这件事。谢谢 我是这样做的:

    Membership.GetUser().UserName
    

    哪条路更快?

        2
  •  2
  •   Community CDub    8 年前

    this thread . 我希望此代码允许您在不了解登录实现的情况下获取身份:

    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();
    
        3
  •  1
  •   changelog    16 年前

    参考 System.Web 和使用 HttpContext.Current.User.Identity.Name