ASP.NET MVC 5: Retrieving the Current ApplicationUser
Accessing the currently logged-in ApplicationUser in ASP.NET MVC 5's Identity framework requires a specific approach. Unlike the Membership mechanism of old, Identity provides a consistent interface for interacting with user data.
Retrieving the ApplicationUser Object
To obtain the full object of the current ApplicationUser, do not directly query the database. Instead, use the provided API:
var user = UserManager.FindById(User.Identity.GetUserId());
For async actions, use:
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
Ensure you have the following using statement included:
using Microsoft.AspNet.Identity;
Accessing the User ID
Outside of a controller, the user ID can be retrieved from:
System.Web.HttpContext.Current.User.Identity.GetUserId();
Scenario: Accessing ApplicationDbContext and UserManager
If you are not in the Account controller, add these properties and the constructor code to your controller:
protected ApplicationDbContext ApplicationDbContext { get; set; } protected UserManager<ApplicationUser> UserManager { get; set; } public YourController() { this.ApplicationDbContext = new ApplicationDbContext(); this.UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.ApplicationDbContext)); }
Azure Database Considerations
When using Identity Framework with a remote Azure database connection, you may encounter the "error: 19 - Physical connection is not usable" message. To resolve this, implement a custom SqlAzureExecutionStrategy in your project.
The above is the detailed content of How to Retrieve the Currently Logged-in ApplicationUser in ASP.NET MVC 5?. For more information, please follow other related articles on the PHP Chinese website!