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.
Published by
Dhananjay Kumar
Dhananjay Kumar is Developer Evangelist for Infragistics. He is a 8 times Microsoft MVP and well respected Developer Advocate in India.He is the author of 900+ Blog Posts, and can often be found speaking around India at conferences and hosting free workshops for programmers across the country. So far, he has hosted 60 free workshops on various topics like JavaScript, Angular, WCF, ASP.NET MVC, C#, Azure etc.
Follow him on twitter @debug_mode for all the updates about his blog posts and workshops. You can send him email at debugmode [at] outlook [dot] com
View all posts by Dhananjay Kumar
This does not work of you log in with User A, log out, and then log in with User B
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);
}
}
how i can get the user name without round tripping db via linq?
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?