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
Release: 2024-12-27 10:52:10
Original
917 people have browsed it

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

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

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

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