Reputation: 3032
I have User class:
public class User : Entity
{
public void AcceptMenu(Menu menu)
{
//AcceptMenu
}
public string Login { get; set; }
public string Password { get; set; }
public string Salt { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
And I create authorization logic. Authenticate method looks like this:
private async Task Authenticate(User user)
{
var claims = new List<Claim>
{
new Claim(ClaimsIdentity.DefaultNameClaimType, user.Login),
new Claim(ClaimsIdentity.DefaultRoleClaimType, user.Role)
};
ClaimsIdentity id = new ClaimsIdentity(claims, "ApplicationCookie", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(id));
}
As you can see I have AcceptMenu method in User. How can I get User in Controller and execute AcceptMenu method?
Upvotes: 2
Views: 897
Reputation: 15
How to get the current logged in user Id in ASP.NET Core Once you get the value from ClaimsPricipal, you can pass the value as a parameter.
Upvotes: 0
Reputation: 58
You can always use var loggedInUser = await useManager.GetUserAsync(User)
to get the user if you are logged in.
Upvotes: 0
Reputation: 1820
Controller has property User with IPrincipal
type. You can get name of user with User.Identity.Name
But it is name of Authenticated asp.net user. You can map this Authenticated user with your user class.
in controller
ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
ApplicationUser user = await UserManager.FindByEmailAsync(User.Identity.Name);
Where ApplicationUserManager is class with identity config , and ApplicationUser is IdentityUser from this class. But it is not your db User derived from entity class, it should be mapped manually
Upvotes: 2