问题描述
我找到了这个链接:
但答案都已经过时了!
这个 SO 帖子也不能成为解决方案,它只是一个样板解决方法:我应该如何从我的 MVC 6 视图中访问我的 ApplicationUser 属性?
And this SO post can not neither be a solution, its just a boilerplate workaround: How should I access my ApplicationUser properties from within my MVC 6 Views?
在 mvc 操作中:base.User 不是 ApplicationUser 类型,base.User.Identity 也不是.两者都不能转换为 ApplicationUser.
In the mvc action: base.User is not of type ApplicationUser neither is base.User.Identity. Both can not be casted into ApplicationUser.
那么我如何在登录时访问我放在 applicationuser 对象中的自定义属性?
So how can I access my custom properties put inside the applicationuser object when logged in?
推荐答案
对于控制器,需要依赖UserManager
.然后,您可以通过请求的 HttpContext 访问 ApplicationUser.我为我的项目写了一个扩展方法:
For the controller, have a dependency on UserManager<ApplicationUser>
. Then, you can access the ApplicationUser through the HttpContext of the request. I wrote an extension method for my project:
public static class IdentityExt
{
public static Task<T> GetCurrentUser<T>(this UserManager<T> manager, HttpContext httpContext) where T: class{
return manager.GetUserAsync(httpContext.User);
}
}
返回当前用户,并允许您访问他们的所有属性.
That returns the current user, and will allow you to access all of their properties.
这是在一个动作里面:
public Task<IActionResult> Index(){
var user = await _userManager.GetCurrentUser(HttpContext);
}
这篇关于从 asp.net 核心标识中获取 applicationuser 的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!