view raw
Jahan Jahan - 9 months ago 111
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
string currentUserId = User.Identity.GetUserId();
User currentUser = DataContextFactory.GetDataContext().Users.FirstOrDefault(x => x.Id.ToString() == currentUserId);
return currentUser;


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

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