Jahan Jahan - 3 months ago 55
ASP.NET (C#) Question

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

Answer

With Identity v2 the best way to get a user is to use the UserManager object.

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