Home > Backend Development > C++ > How to Retrieve the Currently Logged-in ApplicationUser in ASP.NET MVC 5?

How to Retrieve the Currently Logged-in ApplicationUser in ASP.NET MVC 5?

Susan Sarandon
Release: 2024-12-27 21:23:14
Original
238 people have browsed it

How to Retrieve the Currently Logged-in ApplicationUser in ASP.NET MVC 5?

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());
Copy after login

For async actions, use:

var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
Copy after login

Ensure you have the following using statement included:

using Microsoft.AspNet.Identity;
Copy after login

Accessing the User ID

Outside of a controller, the user ID can be retrieved from:

System.Web.HttpContext.Current.User.Identity.GetUserId();
Copy after login

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));
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template