本文介绍了ViewComponent中的Applicationuser的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的viewComponent中获得对applicationUser的访问权限.但是,这不能像从"Controller"继承的普通类一样工作.

I want to get Access to the applicationUser in my viewComponent. However, this doesn´t work like a normal class that inherits from "Controller".

有人知道我如何从ViewComponent访问ApplicationUser吗?

Does anyone know how I can access the ApplicationUser from my ViewComponent?

public class ProfileSmallViewComponent : ViewComponent
{
    private readonly ApplicationDbContext _Context;
    private readonly UserManager<ApplicationUser> _UserManager;

    public ProfileSmallViewComponent(UserManager<ApplicationUser> UserManager, ApplicationDbContext Context)
    {
        _Context = Context;
        _UserManager = UserManager;
    }

    //GET: /<controller>/
    public async Task<IViewComponentResult> InvokeAsync()
    {
        //ApplicationUser CurrentUser = _Context.Users.Where(w => w.Id == _UserManager.GetUserId(User)).FirstOrDefault();
    //Code here to get ApplicationUser

        return View("Header");
    }
}

推荐答案

它的工作原理很像.这是我刚刚测试过的示例:

It works like a charm. Here's your example I just tested:

public class ProfileSmallViewComponent : ViewComponent
{
    private readonly UserManager<ApplicationUser> _userManager;

    public ProfileSmallViewComponent(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    public async Task<IViewComponentResult> InvokeAsync()
    {
        var users = await _userManager.Users.ToListAsync();
        return await Task.FromResult<IViewComponentResult>(View("Header", users));
    }
}

顺便说一句,如果您需要获取当前用户,则只需使用 GetUserAsync 方法,就无需使用 ApplicationDbContext 依赖项:

By the way If you need to get current user, you can simply use GetUserAsync method, there's no need to using ApplicationDbContext dependency:

ApplicationUser currentUser = await _userManager.GetUserAsync(HttpContext.User);

这篇关于ViewComponent中的Applicationuser的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 17:50