c# - 在身份中获取当前用户的电子邮件

标签 c# asp.net-mvc identity

我使用 IIdentity获取电流的接口(interface)useridusername .

所以实现下面的方法:

private static IIdentity GetIdentity()
{
    if (HttpContext.Current != null && HttpContext.Current.User != null)
    {
        return HttpContext.Current.User.Identity;
    }

    return ClaimsPrincipal.Current != null ? ClaimsPrincipal.Current.Identity : null;
}

并添加此代码:_.For<IIdentity>().Use(() => GetIdentity());在我的 IoC 容器中 [structuremap] .

用法

this._identity.GetUserId();
this._identity.GetUserName();
this._identity.IsAuthenticated

现在我要实现GetEmailAdress方法,如何做到这一点?

示例

this._identity.GetEmailAdress();

当使用 this._identity.GetUserName();不要从数据库获取用户名。

最佳答案

你可以在这些行上做一些事情:

public static class IdentityExtensions
{
    public static string GetEmailAdress(this IIdentity identity)
    {
        var userId = identity.GetUserId();
        using (var context = new DbContext())
        {
            var user = context.Users.FirstOrDefault(u => u.Id == userId);
            return user.Email;
        }
    }        
}

然后你就可以访问它了:

this._identity.GetEmailAdress();

关于c# - 在身份中获取当前用户的电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42532765/

相关文章:

c# - 组合来自多个表的数据以在 MVC View 中显示

c# - 在 C# 中获取 session 详细信息的 Outlook API

c# - 为什么 azure 函数看不到配置的连接字符串?

c# - 将 Try-Catch block 添加到 XAML 代码

c# - Asp net 在 View 文件中打印字典值

validation - 重新验证身份后丢失自定义声明

c# - TreeView 仅在复选框处忽略双击

c# - 为每个用户创建不同的静态单例实例

sql-server - SQL Server IDENTITY自增字段是线程安全的吗?

asp.net - HttpContext.Current 在 RegenerateIdentity 期间为空