在 Asp.net Core 中获取 UserManager 类的对象?

Goo*_*eng 2 c# asp.net asp.net-mvc-5 asp.net-core-mvc asp.net-core

using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Services_Website.Models;
using Microsoft.AspNetCore.Mvc;
using Services_Website.Data;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;

namespace Services_Website.CustomFunctions
{
    public class CustomUserOperations: Controller
    {

        private UserManager<ApplicationUser> _userManager;
        public ApplicationUser GetCurrentUser()
        {
            ClaimsPrincipal currentUser = User;
            _userManager = new UserManager<ApplicationUser>();
            var user =_userManager.GetUserAsync(User).Result;
            return user;
        }
    }
}

Run Code Online (Sandbox Code Playgroud)

* 这是我的控制器 *

我只想获取 UserManager 类的对象但是当我这样做时,我收到此错误

错误 CS7036 没有给出与“UserManager.UserManager(IUserStore, IOptions, IPasswordHasher, IEnumerable>, IEnumerable>, ILookupNormalizer, IdentityErrorDescriber, IServiceProvider, ILogger>)' Services_Website F:\webApplication \CoreApp\Services_Website\Services_Website\CustomFunctions\CustomUserOperations.cs 75 活动 *

*错误来源是什么

Ste*_*pUp 6

可以使用依赖注入来获取UserManager类的实例。只需添加参数Configure的方法Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
    UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
{}
Run Code Online (Sandbox Code Playgroud)

然后在控制器中:

public class CustomUserOperations: Controller
{
     private UserManager<ApplicationUser> _userManager;
     CustomUserOperations(UserManager<ApplicationUser> userManager)
     {
         _userManager = userManager;
     }

     public ApplicationUser GetCurrentUser()
     {
         ClaimsPrincipal currentUser = User;
         var user =_userManager.GetUserAsync(User).Result;
         return user;
     }
}
Run Code Online (Sandbox Code Playgroud)

您可以在此处阅读有关依赖项注入的更多信息。