2016-07-20 2 views
2

Использование ядра asp.net, возможно ли получить текущего зарегистрированного пользователя в классе-помощнике тега?Текущий зарегистрированный пользователь в теге 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 *** 

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

ответ

4

Вы можете вводить 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 service is not registered by default, так

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); 
+0

Это работало без регистрации IHttpContextAccessor ... –

Смежные вопросы