gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:47:49 24 4
gpt4 key购买 nike

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;
}
}
}

* 这是我的 Controller *

我只想获取 UserManager 类的一个对象,但是当我这样做时,我得到了这个错误

Error CS7036 There is no argument given that corresponds to the required formal parameter 'store' of 'UserManager.UserManager(IUserStore, IOptions, IPasswordHasher, IEnumerable>, IEnumerable>, ILookupNormalizer, IdentityErrorDescriber, IServiceProvider, ILogger>)' Services_Website F:\webApplication\CoreApp\Services_Website\Services_Website\CustomFunctions\CustomUserOperations.cs 75 Active *

*错误来源是什么

最佳答案

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

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

然后在 Controller 中:

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;
}
}

您可以阅读更多关于 dependency injection here 的信息.

关于c# - 在 Asp.net Core 中获取 UserManager 类的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59065754/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com