简体   繁体   中英

How to find current user within model in asp.net mvc

I have a table for messages and another table for messageviews. I'm looking to show unread messages to an individual user. With my message table, I've sent up a new field that looks to see if any messageviews exist for the current message. If they do, then my Viewed bool should return true otherwise false(if they haven't viewed the message). Everything works fine, except that I'm unable to find the currently logged in user with User.Identity.GetUser() as I normally would. I've added the correct usings as well. Is there some limitation within a model to restrict this type of call. If so, how can I find the current user within a model?

    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;
            }

        }
    }

Resolved: Outside of a controller you can find the current user with this -

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

在控制器外部,您可以使用以下命令找到当前用户:var _userId = System.Web.HttpContext.Current.User.Identity.GetUserId();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM