Home >Backend Development >C++ >How to Retrieve the Current ApplicationUser in ASP.NET MVC 5 Identity?
Unlike the old Membership mechanism, ASP.NET Identity provides an API to access the current user object. Here's how you can get it:
In controllers or other areas where you have access to the default user manager, you can utilize the FindById method:
using Microsoft.AspNet.Identity; public ActionResult Create() { var user = UserManager.FindById(User.Identity.GetUserId()); return View(); }
If you're outside controllers, you can use the following code:
using Microsoft.AspNet.Identity; using System.Web; public class MyCustomService { private HttpContext _httpContext; public MyCustomService(HttpContext httpContext) { _httpContext = httpContext; } public ApplicationUser GetCurrentUser() { var userId = _httpContext.User.Identity.GetUserId(); var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); return userManager.FindById(userId); } }
This method may be necessary when accessing the current user from the OWIN context, such as from SignalR Hubs or in other scenarios where the standard mechanisms are not available:
using Microsoft.AspNet.Identity; using System.Web; public class MySignalRHub : Hub { public ApplicationUser GetCurrentUser() { var user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId()); return user; } }
The above is the detailed content of How to Retrieve the Current ApplicationUser in ASP.NET MVC 5 Identity?. For more information, please follow other related articles on the PHP Chinese website!