Roberto Correia Roberto Correia - 1 year ago 107
C# Question

Get current user in a TagHelper

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


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
on this class, only a


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
, but this is avaliable only on Controller class.


Answer Source

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(HttpContext.User);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download