你可以扩展HttpContext.Current.User.Identity性能 [英] Can you extend HttpContext.Current.User.Identity properties

查看:652
本文介绍了你可以扩展HttpContext.Current.User.Identity性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法覆盖 HttpContext.Current.User.Identity 添加其他财产(网名)?

Is there a way to override HttpContext.Current.User.Identity to add another property (screen name)?

我的应用程序使用身份,我已经离开了独特的身份,电子邮件。我存储用户数据,例如在一个单独的档案表姓/名。有没有一种办法,以地方在 HttpContext.Current 存储这些信息?

My application uses Identity and I've left the unique identity as email. I store user data such as first / last name in a separate "Profile" table. Is there a way to store this information somewhere within HttpContext.Current?

这并不一定需要是用户之内。我有一个搜索,发现有一个 HttpContext.Current.ProfileBase 。不知道如何使用,虽然它 - 我真的不希望所有的多余的东西,基地配备了

It doesn't necessarily need to be within User. I have had a search and noticed there's a HttpContext.Current.ProfileBase. Not sure how to use it though - and I really don't want all the excess stuff that base comes with.

推荐答案

如果您使用的是Asp.Net的身份,那么这是很容易与索赔的事情。

If you are using Asp.Net Identity, then this is very easy to do with claims.

在你的 SignInAsync 方法(或者,无论你正在创建的声明身份),添加给定名称声明类型:

In your SignInAsync method (or, wherever you are creating the claims identity), add the GivenName and Surname claim types:

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);

    var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

    // Add the users primary identity details to the set of claims.
    var your_profile = GetFromYourProfileTable();

    identity.AddClaim(new Claim(ClaimTypes.GivenName, your_profile == null ? string.Empty : your_profile.FirstName));
    identity.AddClaim(new Claim(ClaimTypes.Surname, your_profile == null ? string.Empty : your_profile.LastName));

    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}

您然后使用扩展方法的IIdentity 拉出的信息索赔身份:

You then use an extension method to IIdentity to pull the information out of the claims identity:

public static ProfileName GetIdentityName(this IIdentity identity)
{
    if (identity == null)
        return null;

    var first = (identity as ClaimsIdentity).FirstOrNull(ClaimTypes.GivenName),
    var last = (identity as ClaimsIdentity).FirstOrNull(ClaimTypes.Surname)

    return string.Format("{0} {1}", first, last).Trim();
}

internal static string FirstOrNull(this ClaimsIdentity identity, string claimType)
{
    var val = identity.FindFirst(claimType);

    return val == null ? null : val.Value;
}

然后,在你的应用程序(在控制器或视图),你可以做:

Then, in your application (in your controller or view), you can just do:

var name = User.Identity.GetIdentityName();

这篇关于你可以扩展HttpContext.Current.User.Identity性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆