Accessing Current User Details in ASP.NET MVC Applications
Older ASP.NET applications relied on Page.CurrentUser
to identify the logged-in user. This method is unsuitable for ASP.NET MVC applications due to their controller-based request handling.
The Solution:
Within an ASP.NET MVC controller, the User
property of the Controller
base class provides access to the authenticated user's data via a ClaimsPrincipal
object:
<code class="language-csharp">public class HomeController : Controller { public ActionResult Index() { // Access the authenticated user's ClaimsPrincipal ClaimsPrincipal currentUser = User; //Further processing of currentUser... } }</code>
For views, you can either pass the necessary user information via ViewData
or directly use the User
property:
<code class="language-csharp">// Within the controller: ViewData["UserName"] = User.Identity.Name; // In the view: @ViewData["UserName"] // Displays the logged-in user's name</code>
The above is the detailed content of How Do I Retrieve the Currently Logged-in User in ASP.NET MVC?. For more information, please follow other related articles on the PHP Chinese website!