Monday, February 2, 2015

Get the Current Logged in user

In ASP.NET MVC if you are using Asp.Net Identities, you will need to at times get the current logged in user. You may need to do this to determine whether the current logged in user has access to view, create, modify records etc...

First of all this can be only completed in the Controller. If you need the user inside of another class, you will need to pass this through to the class method/function etc...

In the controller, header set the following properties:

   protected ApplicationDbContext Db { get; set; }
   protected UserManager<ApplicationUser> UM { get; set; }
Then in the class Constructor add the following lines:
this.Db = new ApplicationDbContext();
    this.UM = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.Db));

Once you have done this, you can then get the user within the controller using the following :
var user = UM.FindById(User.Identity.GetUserId());

The user will be of type ApplicationUser.

0 comments:

Post a Comment