Beetlejuice
Beetlejuice

Reputation: 4425

Current logged user in tag helper

Using asp.net core, is it possible to get the current logged user in a tag helper class?

lets suppose this tag helper:

[HtmlTargetElement("lesson")]
public class LessonTagHelper : BaseTagHelper
{
    private readonly ILessonServices lessonService;
    private readonly UserManager<ApplicationUser> userManager;

    public LessonTagHelper(ILessonServices lessonService, UserManager<ApplicationUser> userManager)
    {
        this.lessonService = lessonService;
        this.userManager = userManager;
    }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {            
        base.Process(context, output);
        output.TagName = "div";

        *** I NEED USER HERE *** 

I know that in the controller we have a "User" property ready to use, but it is not available in other classes.

Upvotes: 1

Views: 857

Answers (1)

tmg
tmg

Reputation: 20393

You can inject IHttpContextAccessor into LessonTagHelper

private readonly ILessonServices lessonService;
private readonly UserManager<ApplicationUser> userManager;
private readonly IHttpContextAccessor httpContextAccessor;

public LessonTagHelper(ILessonServices lessonService, UserManager<ApplicationUser> userManager, IHttpContextAccessor httpContextAccessor)
{
        this.lessonService = lessonService;
        this.userManager = userManager;
        this.httpContextAccessor = httpContextAccessor;
}

and then where you need you can access User like httpContextAccessor.HttpContext.User ...

Do not forget that IHttpContextAccessor service is not registered by default, so

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Upvotes: 4

Related Questions