使用asp.net核心,是否可以将当前登录的用户置于标记帮助程序类中?
让我们假设这个标签帮助者:
if var1 < [var2 thru var3] < var4
我知道在控制器中我们有一个&#34;用户&#34;属性可以使用,但在其他类中不可用。
答案 0 :(得分: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>();