programing

ASP.NET Identity 2.0에서 현재 사용자 ID 가져오기

starjava 2023. 6. 21. 22:01
반응형

ASP.NET Identity 2.0에서 현재 사용자 ID 가져오기

방금 새로운 2.0 버전의 Identity Framework 사용으로 전환했습니다.1.0에서 나는 사용자 객체를 얻을 수 있었습니다.manager.FindByIdAsync(User.Identity.GetUserId()).그GetUserId()메서드가 2.0에 존재하지 않는 것 같습니다.

이제 내가 알아낼 수 있는 것은manager.FindByEmailAsync(User.Identity.Name)사용자 테이블의 사용자 이름 필드를 참조합니다.내 응용프로그램에서 이 필드는 전자 메일 필드와 동일하게 설정됩니다.

누군가 이메일을 업데이트해야 할 때 문제가 발생하는 것을 볼 수 있습니다.Identity 2.0 Framework에서 변경되지 않는 값(예: ID 필드)을 기반으로 현재 로그인한 사용자 개체를 가져올 수 있는 방법이 있습니까?

GetUserId()의 확장 메서드입니다.IIdentity그리고 그것은.Microsoft.AspNet.Identity.IdentityExtensions네임스페이스를 추가했는지 확인하십시오.using Microsoft.AspNet.Identity;.

Asp.net Identity 2.0에서 CurrentUserId를 가져오려면 처음 가져올 때Microsoft.AspNet.Identity:

C#:

using Microsoft.AspNet.Identity;

VB.NET:

Imports Microsoft.AspNet.Identity


그리고 나서 전화.User.Identity.GetUserId()원하는 모든 곳에서:

strCurrentUserId = User.Identity.GetUserId()

이 메서드는 현재 사용자 ID를 데이터베이스의 사용자 ID에 대해 정의된 데이터 유형으로 반환합니다(기본값:String).

만약 당신이 나와 같으며 사용자 엔티티의 Id 필드가 Int 또는 문자열이 아닌 다른 것인 경우,

using Microsoft.AspNet.Identity;

int userId = User.Identity.GetUserId<int>();

성공할 것입니다

저도 같은 문제가 있었습니다.저는 현재 Asp.net Core 2.2를 사용하고 있습니다.저는 이 문제를 다음 코드로 해결했습니다.

using Microsoft.AspNetCore.Identity;
var user = await _userManager.FindByEmailAsync(User.Identity.Name);

저는 이것이 누군가에게 유용하기를 바랍니다.

클레임을 사용하여 로그인한 사용자의 userId, 사용자 이름 및 이메일을 받았습니다.

            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); // will give the user's userId
        //userName = User.FindFirstValue(ClaimTypes.Name); // will give the user's userName
        //email = User.FindFirstValue(ClaimTypes.Email);

언급URL : https://stackoverflow.com/questions/22624470/get-current-user-id-in-asp-net-identity-2-0

반응형