在分机 class 获取用户管理器

Get user manager at extension class

我正在将我的 ASP.net MVC 项目迁移到核心版本。我有一个扩展 class 方法,returns 用户名按用户 ID (Guid)。

public static class IdentityHelpers
{
    public static MvcHtmlString GetUserName(this HtmlHelper html, string id)
    {
        var manager = HttpContext.Current
            .GetOwinContext().GetUserManager<AppUserManager>();

        return new MvcHtmlString(manager.FindByIdAsync(id).Result.UserName);
    }
}

因为我正在将其重写为 .NET Core,所以我不知道如何在此处获取用户管理器实例。通常我会通过 DI 注入它,但我不知道该怎么做,因为我正在使用扩展方法,所以我无法注入它。

如何在静态 class 中获得 UserManager

新版本发生了变化。通过 HtmlHelper.ViewContext 访问当前 HttpContext,从那里您应该能够访问可用于解析服务的 IServiceProvider

public static class IdentityHelpers {
    public static MvcHtmlString GetUserName(this HtmlHelper html, string id) {
        HttpContext context = html.ViewContext.HttpContext;
        IServiceProvider services = context.RequestServices;
        var manager = services.GetService<AppUserManager>();

        return new MvcHtmlString(manager.FindByIdAsync(id).Result.UserName);
    }
}