简体   繁体   中英

Accessing the logged in User's fields from the controller when using ASP.NET Identity with MVC6

I have an ASP.NET MVC 6 web application. I am using Dapper for everything but Users. For users I am using the built-in Identity along with EntityFramework just the way Microsoft gives it to you.

I am saving a new product to the database using dapper. After saving that product in my controller, the new product model is returned, but I need to set the current User's FirstName and LastName before returning it to the view model.

I know one way would be to use Dapper to make another database call, something like GetUserByUsername which would go out to the AspNetUsers table and retrieve and bind whichever properties I want. Since my Project's Model for dapper is separate, In this case I would most likely create another Model class called User, rather than using the ApplicationUser class.

Should I really have to do this though? If I can get the current logged in Username using User.Identity.Name, is there any built in Identity function I can use to actually retrieve the entire user?

You should be able use the UserManager class https://msdn.microsoft.com/en-us/library/dn613290(v=vs.108).aspx

Once you instantiate the manager you should be able to use a query like below _userManager.Users.Single(a => a.UserName == "XXXXXX");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM