programing

현재 사용자를 얻는 방법과 MVC5에서 사용자 클래스를 사용하는 방법은 무엇입니까?

telecom 2023. 6. 4. 10:17
반응형

현재 사용자를 얻는 방법과 MVC5에서 사용자 클래스를 사용하는 방법은 무엇입니까?

  • MVC 5에서 현재 로그인한 사용자의 ID는 어떻게 얻을 수 있습니까?StackOverflow 제안을 해봤지만 MVC 5용은 아닌 것 같습니다.
  • 또한 사용자에게 물건을 할당하는 MVC 5 모범 사례는 무엇입니까?(예: a)User했어야 했습니다Items사용자의 데이터를 저장해야 합니까?Id안에Item연장할 수 있습니까?User과의 수업.List<Item>내비게이션 속성?

MVC 템플릿의 "개별 사용자 계정"을 사용하고 있습니다.

사용해 본 내용:

'멤버십.GetUser()'가 null입니다.

ASP.NET MVC 컨트롤러에서 코딩하는 경우

using Microsoft.AspNet.Identity;

...

User.Identity.GetUserId();

언급할 가치가 있습니다.User.Identity.IsAuthenticated그리고.User.Identity.Name위에서 언급한 내용을 추가하지 않고 작동합니다.using진술.그렇지만GetUserId()그것 없이는 참석할 수 없을 것입니다.

컨트롤러가 아닌 클래스에 있는 경우

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

MVC 5의 기본 템플릿에서 사용자 ID는 문자열로 저장된 GUID입니다.

모범 사례는 아직 없지만 사용자 프로필 확장에 대한 유용한 정보를 찾았습니다.

다음과 같은 방법을 사용해 보십시오.

var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
var userManager = new UserManager<ApplicationUser>(store);
ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result;

RTM과 함께 작동합니다.

ApplicationUser 개체를 한 줄의 코드로 사용하려면(최신 ASP.NET Identity가 설치된 경우) 다음을 시도하십시오.

ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

문을 사용하여 다음이 필요합니다.

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

ID를 얻는 것은 꽤 직접적이고 당신은 그것을 해결했습니다.

하지만 당신의 두 번째 질문은 조금 더 관련이 있습니다.

따라서 지금은 모두 사전 릴리스 항목이지만 일반적으로 직면한 문제는 새 속성(또는 해당 항목 모음)으로 사용자를 확장하는 경우입니다.

박스에서 나온 파일은 다음과 같습니다.IdentityModel모델 폴더 아래에 있습니다(작성 시점).거기에는 몇 가지 수업이 있습니다.ApplicationUser그리고.ApplicationDbContext의 컬렉션을 추가하려면 다음과 같이 하십시오.Items당신은 수정하고 싶을 것입니다.ApplicationUser클래스, Entity Framework에서 사용하는 일반 클래스와 동일한 클래스입니다.실제로 후드 아래에서 간단히 살펴보면 ID와 관련된 모든 클래스(사용자, 역할 등)가 이제 적절한 데이터 주석을 가진 POCO에 불과하므로 EF6를 잘 사용할 수 있습니다.

다음으로, 몇 가지 변경 사항을 적용해야 합니다.AccountController생성자가 DbContext 사용 방법을 알 수 있도록 합니다.

public AccountController()
{
    IdentityManager = new AuthenticationIdentityManager(
    new IdentityStore(new ApplicationDbContext()));
}

이제 로그인한 사용자의 전체 사용자 개체를 가져오는 것은 솔직히 좀 난해합니다.

    var userWithItems = (ApplicationUser)await IdentityManager.Store.Users
    .FindAsync(User.Identity.GetUserId(), CancellationToken.None);

그줄일을끝것당접수것있다입니을속할은신이고낼은다에 접속할 수 입니다.userWithItems.Items당신이 원하는 대로.

HTH

당신의 고통을 느껴요, 저도 같은 일을 하려고 노력하고 있어요.이 경우에는 사용자를 삭제하고 싶습니다.

모든 컨트롤러가 상속되는 기본 컨트롤러 클래스를 만들었습니다.그 안에서 나는 무시합니다.OnAuthentication 설합니다를 합니다.filterContext.HttpContext.User to null

그게 지금까지 내가 해온 최선을 다했습니다.

public abstract class ApplicationController : Controller   
{
    ...
    protected override void OnAuthentication(AuthenticationContext filterContext)
    {
        base.OnAuthentication(filterContext); 

        if ( ... )
        {
            // You may find that modifying the 
            // filterContext.HttpContext.User 
            // here works as desired. 
            // In my case I just set it to null
            filterContext.HttpContext.User = null;
        }
    }
    ...
}
        string userName="";
        string userId = "";
        int uid = 0;
        if (HttpContext.Current != null && HttpContext.Current.User != null
                  && HttpContext.Current.User.Identity.Name != null)
        {
            userName = HttpContext.Current.User.Identity.Name;              
        }
        using (DevEntities context = new DevEntities())
        {

              uid = context.Users.Where(x => x.UserName == userName).Select(x=>x.Id).FirstOrDefault();
            return uid;
        }

        return uid;

다른 사람들이 이런 상황을 겪고 있는 경우: 사용자가 아직 로그인하지 않도록 앱에 로그인하기 위한 이메일 확인을 작성하고 있지만, 아래를 사용하여 로그인에 입력된 @firecape 솔루션의 변형인 이메일을 확인했습니다.

 ApplicationUser user = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindByEmail(Email.Text);

또한 다음이 필요합니다.

using Microsoft.AspNet.Identity;

그리고.

using Microsoft.AspNet.Identity.Owin;

.Net MVC5 코어 2.2에서는 HttpContext를 사용합니다.사용자. 신원.이름. 저한테는 효과가 있었어요.

이것이 AsNetUserId를 가져와서 홈 페이지에 표시하는 방법입니다.

HomeControllerIndex() 메서드에 다음 코드를 배치했습니다.

ViewBag.userId = User.Identity.GetUserId();

보기 페이지에서 그냥 전화하세요.

ViewBag.userId 

프로젝트를 실행하면 userId를 볼 수 있습니다.

언급URL : https://stackoverflow.com/questions/18448637/how-to-get-current-user-and-how-to-use-user-class-in-mvc5

반응형