Текущий зарегистрированный пользователь в помощнике по тегам

Используя ядро ​​​​asp.net, можно ли получить текущего зарегистрированного пользователя в вспомогательном классе тегов?

давайте предположим, что этот помощник тега:

[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 *** 

Я знаю, что в контроллере у нас есть свойство «Пользователь», готовое к использованию, но оно недоступно в других классах.


person Beetlejuice    schedule 20.07.2016    source источник


Ответы (1)


Вы можете внедрить IHttpContextAccessor в 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;
}

а затем, где вам нужно, вы можете получить доступ к Пользователю, например httpContextAccessor.HttpContext.User ...

Не забывайте, что служба IHttpContextAccessor по умолчанию не зарегистрирована, поэтому

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
person tmg    schedule 21.07.2016