简体   繁体   中英

Fast way to get current user in ASP.NET Identity

What is the fast way (best way) to get current user in ASP.NET Identity?

I wrote this code for getting current user but I don't know that is the best way or not?

public class MVCController : Controller
{
    public User CurrentUser
    {
        get
        {
            string currentUserId = User.Identity.GetUserId();
            User currentUser = DataContextFactory.GetDataContext().Users.FirstOrDefault(x => x.Id.ToString() == currentUserId);
            return currentUser;
        }
    }
}

对于Identity v2,获取用户的最佳方法是使用UserManager对象。

var user = userManager.FindById(user.Identity.GetUserId());

Rather than a DB hit, we should add all required information in user claims during authentication and retrieve them from claims during next calls. It will be the fastest way to get commonly used user information and the same time we avoid any database calls. You can take a look on some claims helper methods Github link

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