2016-10-04 84 views
0

我有一个消息表和另一个messageviews表。我正在寻找向个人用户显示未读消息。通过我的消息表,我发送了一个新字段,用于查看当前消息是否存在任何消息浏览。如果他们这样做,那么我的视图布尔应该返回true否则为false(如果他们没有查看消息)。一切工作正常,除了我无法找到User.Identity.GetUser()我目前登录的用户通常。我也添加了正确的用法。在模型中是否存在限制这种类型的呼叫的限制。如果是这样,我怎么才能找到模型中的当前用户?如何在asp.net中查找模型中的当前用户mvc

public bool Viewed 
    { 
     get 
     { 
      ApplicationDbContext db = new ApplicationDbContext(); 
      //var _userId = User.Identity.GetUserId(); 
      var _userId = Thread.CurrentPrincipal.Identity.GetUserId(); 
      List<MessageView> m_List = db.MessageView.Where(u => u.UserId == _userId && u.MessageId == O_MessageId).ToList(); 
      var count = m_List.Count(); 
      if (count >= 1) 
      { 
       return true; 
      } 
      else 
      { 
       return false; 
      } 

     } 
    } 

解决:控制器之外你可以找到与该当前用户 -

变种_userId = System.Web.HttpContext.Current.User.Identity.GetUserId();

+1

您使用的是异步方法吗?你可以展示一些你的代码,看看我们能否更好地帮助你? –

+0

尝试'Thread.CurrentPrincipal.Identity.GetUserId()' – GauravKP

+0

我得到错误,线程在当前上下文中不存在。我已经在上面添加了我的支票。 – DudeThatCodes

回答

0

在控制器之外,您可以通过以下方式找到当前用户: var _userId = System.Web.HttpContext.Current.User.Identity.GetUserId();

+0

不要忘记包括使用Microsoft.AspNet.Identity; – Kyle