Home >Backend Development >C++ >How to Retrieve the Current ApplicationUser in ASP.NET MVC 5 Identity?

How to Retrieve the Current ApplicationUser in ASP.NET MVC 5 Identity?

Barbara Streisand
Barbara StreisandOriginal
2024-12-27 10:52:10890browse

How to Retrieve the Current ApplicationUser in ASP.NET MVC 5 Identity?

How to Get 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:

Using UserManager

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();
}

In Non-Controllers

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);
    }
}

Using Owin Context (March 2015 Update)

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!

Statement:
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