【问题标题】:Get property of applicationuser from the asp.net core identity从 asp.net 核心标识中获取 applicationuser 的属性
【发布时间】:2016-08-26 20:20:20
【问题描述】:

我找到了这个链接:

How to get the current logged in user Id ASP.NET Core

但答案都已经过时了!

这个 SO 帖子也不能成为解决方案,它只是一个样板解决方法:How should I access my ApplicationUser properties from within my MVC 6 Views?

在 mvc 操作中:base.User 不是 ApplicationUser 类型,base.User.Identity 也不是。两者都不能转换为 ApplicationUser。

那么我如何在登录时访问我放在 applicationuser 对象中的自定义属性?

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc


    【解决方案1】:

    对于控制器,依赖于UserManager<ApplicationUser>。然后,您可以通过请求的 HttpContext 访问 ApplicationUser。我为我的项目写了一个扩展方法:

     public static class IdentityExt
     {
        public static Task<T> GetCurrentUser<T>(this UserManager<T> manager, HttpContext httpContext) where T: class{
            return manager.GetUserAsync(httpContext.User);
        }
     }
    

    返回当前用户,并允许您访问他们的所有属性。

    这是在一个动作里面:

    public Task<IActionResult> Index(){
         var user = await _userManager.GetCurrentUser(HttpContext);
    }
    

    【讨论】:

    • f..k...我尝试了GetUserIdAsync,之前它只接受一个ApplicationUser,但我不知道如何获取/转换它...为什么没有重载GetUserIdAsync(base.User ) 方法 ?愚蠢的......谢谢Mike_G!起初我试图获取用户的 ID,然后我想如何实际获取自定义属性然后在这里做了问题:-)
    • @Mike_G...不错的扩展方法。我是网络开发的新手。管道中获取用户对象的最佳位置是什么/在哪里,因此它始终可用并且只需要检索一次。每次需要时都必须请求用户对象似乎是重复的。
    猜你喜欢
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    • 2017-01-13
    • 2015-04-24
    • 2022-01-19
    • 2017-07-17
    相关资源
    最近更新 更多