How to get current user in ASP.Net MVC 5

There are two simple ways to get current user in MVC 5. If you are inside the controller class current user can be fetched as follows,


string userId = User.Identity.GetUserId();

Do not forget to add namespace,

 


using Microsoft.AspNet.Identity;

Other scenario could be that you are not inside the controller class and want to fetch the user information. You can fetch that using HttpContext class.

HttpContext.Current.User.Identity.GetUserId();

I hope it helps. Happy Coding.

5 responses to “How to get current user in ASP.Net MVC 5”

  1. […] the last post I talked about How to get current user in ASP.Net MVC 5 . Type of the current user is IPrincipal which is shown as […]

  2. This does not work of you log in with User A, log out, and then log in with User B

  3. it will work 100%
    if(System.Web.HttpContext.Current.User.Identity.IsAuthenticated==true)
    {
    AuthPrincipals auth_users = (AuthPrincipals)System.Web.HttpContext.Current.User;
    if (auth_users != null)
    {
    userid = Convert.ToInt32(auth_users.UserId);
    }
    }

  4. how i can get the user name without round tripping db via linq?

  5. I have extended and added properties to my ASP MVC identity 2.2 in MVC 5, how can I access that from my controller like I added property – CompanyName ->to ASP userstaable

    I want to get that in my controlled?

Leave a comment

Create a website or blog at WordPress.com