sourcecode

Asp에서 로그인한 사용자의 사용자 ID를 가져옵니다.넷 MVC 5

codebag 2023. 8. 11. 21:47
반응형

Asp에서 로그인한 사용자의 사용자 ID를 가져옵니다.넷 MVC 5

저는 ASP가 비교적 생소합니다.지금 MVC를 설정하고 내장된 사용자 로그인 기능을 사용해 보십시오.등록 보기에서 사용자를 등록할 수 있습니다.생성된 사용자와 로그인하려고 하면 이 작업도 수행됩니다.마스터 페이지로 리디렉션됩니다.

하지만 현재 사용자의 사용자 ID를 가져올 수 없습니다.홈 컨트롤러와 계정 컨트롤러에서 코드를 시도했지만 둘 다 작동하지 않았습니다.첫 번째 줄의 문은 항상 null을 반환합니다.

var userID = User.Identity.GetUserId();

if (!string.IsNullOrEmpty(userID))
{
    var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ApplicationDbContext.Create()));
    var currentUser = manager.FindById(User.Identity.GetUserId());
}

사용자 ID를 얻기 전에 다른 작업을 수행해야 합니까?

정답은 바로 당신의 코드 안에 있습니다.이것은 무엇을 반환합니까?

var userID = User.Identity.GetUserId();

ASP를 사용하는 경우.NET Identity 로그인 후(및 다른 페이지로 리디렉션)IPrincipal.IIdentity가 되어야 합니다.ClaimsIdentity사용해 볼 수 있습니다.

var claimsIdentity = User.Identity as ClaimsIdentity;
if (claimsIdentity != null)
{
    // the principal identity is a claims identity.
    // now we need to find the NameIdentifier claim
    var userIdClaim = claimsIdentity.Claims
        .FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);

    if (userIdClaim != null)
    {
        var userIdValue = userIdClaim.Value;
    }
}

위의 코드 블록은 정확하지 않지만 본질적으로 무엇입니까?IIdentity.GetUserId확장 메서드는 합니다.

이 중 하나라도 작동하지 않으면 사용자가 아직 사이트에 로그인하지 않았을 수 있습니다.로그인 후 서버가 브라우저에 인증 쿠키를 쓰기 전에 다른 페이지로 리디렉션해야 합니다.이 쿠키는 다음 이전에 작성되어야 합니다.User.Identity이 모든 청구 정보를 가지고 있습니다(포함).NameIdentifier)을 클릭합니다.

언급URL : https://stackoverflow.com/questions/26739778/get-userid-of-logged-in-user-in-asp-net-mvc-5

반응형