Using MVC 5.
I'm new to Users
, Identities
and Claims
.
How do I get the AspNetUser
from the HttpContext.Current.User
? I know that I can use HttpContext.Current.User.Identity.Name
(which is the email address of the user on my system) and then hit the AspNetUser
table for that user but is there a better way to get the AspNetUser
from the HttpContext.Current.User
that I'm missing? e.g. is it contained somewhere in HttpContext.Current.User
already?
I've tried to Google but I'm not really finding any answers to this specific question.
The AspNetUser isn't stored in HttpContext.Current.User property. An IPrincipal object is returned by HttpContext.Current.User, and the only members specified on IPrincipal are IIdentity Identity and bool IsInRole. The IIdentity interface then provides you with the Name property, which you can use to lookup the actual user object with.
If you just want one line of code and have full access to the User object, you can access the AspNetUser with the following code:
ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
You'll need the following using statements:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
Just note that it's probably better to go through the UserManager API if you're able to, and once you have your User object, you can edit and then save changes via the UserManager update methods. Many changes can be made directly through the UserManager methods. If you have an instance of UserManager around, you can also access the User object by:
ApplicationUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With