web-dev-qa-db-ja.com

ASP.NETIdentityの現在のユーザーを表示する

ASP.NET Identity2.0とMVCを使用しています。ユーザーの名前、姓、メールアドレスなどを表示する必要があります。どうすれば入手できますか? @ User.Identityだけを取得できますが、ユーザークラスのプロパティはありません。

//in my view, i need here my ApplicationUser class
<div>
@User.Identity.Name
</div>

//ApplicationUser class
public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole,
CustomUserClaim> 
{
    public ApplicationUser()
    {
        this.CreatedDate = DateTime.Now;
    }

    public DateTime CreatedDate { get; set; }

    public string Name { get; set; }

    public string Surname { get; set; }

    public string TaxOffice { get; set; }
}
13
Yargicx

取得する必要のある特定のプロパティのみがある場合は、次の例のように、それらをApplicationUserクラスのクレームとして追加できます。

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
{
    // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
    var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
    // Add custom user claims here
    userIdentity.AddClaim(new Claim("FullName", this.FullName));
    // or use the ClaimTypes enumeration
    return userIdentity;
}

これは、Startup.Authクラスから接続されます。

    SessionStateSection sessionStateSection = ConfigurationManager.GetSection("system.web/sessionState") as SessionStateSection;
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/account/login"),
        CookieName = sessionStateSection.CookieName + "_Application",
        Provider = new CookieAuthenticationProvider
        {
            // Enables the application to validate the security stamp when the user logs in.
            OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int>
                (
                     validateInterval: TimeSpan.FromMinutes(30),
                     regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                     getUserIdCallback: (id) => (id.GetUserId<int>())
                ) 

        }
    });

次に、(ビューまたはコントローラーで)クレームにアクセスできます。

var claims = ((System.Security.Claims.ClaimsIdentity)User.Identity).Claims;
var claim = claims.SingleOrDefault(m => m.Type == "FullName");

ここにはフォーム認証チケットはありません。

ユーザーの完全な詳細を利用できるようにしたい場合は、いつでも次のような拡張メソッドを作成できます。

public static ApplicationUser GetApplicationUser(this System.Security.Principal.IIdentity identity)
{
    if (identity.IsAuthenticated)
    {
        using (var db = new AppContext())
        {
            var userManager = new ApplicationUserManager(new ApplicationUserStore(db));
            return userManager.FindByName(identity.Name);
        }
    }
    else
    {
        return null;
    }        
}

そしてそれをこのように呼んでください:

@User.Identity.GetApplicationUser();

ただし、これをずっと呼び出す場合は、キャッシュすることをお勧めします。

19
ScottE

これを実現するには2つの方法があります。

1)CustomPrincipalインターフェースを継承してIPrincipalName、およびSurnameを含めることにより、独自のEmailを作成します this =例または this 1つ。

2)データベースから直接詳細を取得し、モデルとしてビューに渡します。

複数のビューで同じユーザーの詳細を使用する場合は、方法1が適切なオプションですが、これを実現する最も簡単な方法は方法2です。 2番目の方法のコードヘルプが必要な場合はお知らせください。

4
DSR

。NET Coreアプリを使用している場合:

簡単に使用できます@injectUserManagerSignInManagerの両方を注入するための機能呼び出し。

あなたの見解では以下を追加してください:

@inject SignInManager<YourUserIdentity> SignInManager
@inject UserManager<YourUserIdentity> UserManager

インジェクション後、UserManagerおよびSignInManagerメソッドを使用できるようになります。例えば:

@if (SignInManager.IsSignedIn(User))
{
    <a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)</a>
}
else
{
}

現在ログインしているユーザーを参照する必要がある場合は、Userオブジェクトを渡すことに注意してください。

これが誰にとっても便利になることを願っています:)

3
Adir Ratzon

コントローラからユーザーに関する情報を取得するには、使用する必要があります

User.Identity.GetUserId();

または、クラス内のユーザーに関する情報を取得する場合

HttpContext.Current.User.Identity.GetUserId();
0
minenhle