我希望实现类似描述的here,但我有两个问题:在我的控制器的构造函数上,HttpContext
因此User
都是null,我可以好像到了那个UserManager<T>
班......
在我的控制器操作上,我可以获得User
和HttpContext
,但我不想逐个处理声明转换!我想创建一个“BaseController”,有一个“MyExtendedUserPrincipal”,并且我的操作只读取它的内容......
我没有使用常规SQL用户管理中间件...我想这就是为什么我无法掌握UserManager<T>
答案 0 :(得分:1)
UserManager<T>
课程不是开箱即用的,您必须自己定义。您可以使用默认实现,也可以根据需要定义自己的类。
例如:
<强> MyUserStore.cs 强>
这是用户来自的地方(例如数据库),您可以从ClaimsPrincipal
的任何声明中检索自己的用户。
public class MyUserStore: IUserStore<MyUser>, IQueryableUserStore<MyUser>
{
// critical method to bridge between HttpContext.User and your MyUser class
public async Task<MyUser> FindByIdAsync(string userId, CancellationToken cancellationToken)
{
// that userId comes from the ClaimsPrincipal (HttpContext.User)
var user = _users.Find(userId);
return await Task.FromResult(user);
}
}
<强> Startup.cs 强>
public void ConfigureServices(IServiceCollection services)
{
// you'll need both a user and a role class. You can also implement a RoleStore if needed
services
.AddIdentity<MyUser, MyRole>()
.AddUserStore<MyUserStore>();
services.Configure<IdentityOptions>(options =>
{
// This claim will be used as userId in MyUserStore.FindByIdAsync
options.ClaimsIdentity.UserIdClaimType = ClaimTypes.Name;
});
}
MyController .cs
然后,在您的控制器中,您可以访问UserManager<MyUser>
类:
public class MyController : Controller
{
private readonly UserManager<User> _userManager;
public MyController(UserManager<User> userManager)
{
_userManager = userManager;
}
[HttpGet("whatever")]
public async Task<IActionResult> GetWhatever()
{
// this will get your user from the UserStore,
// based on the ClaimsIdentity.UserIdClaimType from the ClaimsPrincipal
MyUser myUser = await _userManager.GetUserAsync(User);
}
}