Reputation: 1726
In a C# (ASP.NET Core) project, after login, the site must list a menu with a submenu according with permissions of the user. This menu appear in all sites. Basically is a dashboard menu.
The content of this menu (submenus) are dynamically, according with user's permission.
So, I think in creating a TagHelper class, that get the current logged user, get the content that this user has permission, and create the content of submenu (somes <ul>
and <li>
).
I don't know if this is the best approach. I accept suggestions.
But, if this approach is OK to use, how I can get the current logged user on a TagHelper class?
I don't have a HttpContext
on this class, only a TagHelperContext
.
TagHelper:
public class UserContentTagHelper : TagHelper
{
private readonly UserManager<ApplicationUser> _userManager;
public UserContentTagHelper(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
output.TagMode == TagMode.SelfClosing;
// Error. HttpContext.User not avaliable
var uid = _userManager.GetUserId(HttpContext.User);
}
}
Normally to get the currently logged user, I use HttpContext.User
, but this is avaliable only on Controller class.
Thanks!
Upvotes: 3
Views: 1031
Reputation: 34992
Add an IActionContextAccessor
parameter to your constructor. You can then get the HttpContext and its associated user with:
var user = actionAccessor.ActionContext.HttpContext.User;
var uid = _userManager.GetUserId(user);
You will also need to register the IActionContextAccessor
in your ConfigureServices method of the Startup class:
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
Upvotes: 8