programing tip

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

itbloger 2020. 6. 7. 10:37
반응형

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


  • MVC 5 에서 현재 로그인 한 사용자의 ID를 어떻게 얻을 수 있습니까? StackOverflow 제안을 시도했지만 MVC 5가 아닌 것 같습니다.
  • 또한 사용자에게 물건을 할당하는 MVC 5 모범 사례는 무엇입니까? (예를 들어 User있어야한다 Items.해야 내가 저장 한 사용자 IdItem? 깡통 나는 연장 User와 클래스를 List<Item>탐색 속성?

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

이것을 시도했다 :

'Membership.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 문이 필요합니다.

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

ID를 얻는 것은 매우 간단하며 해결했습니다.

두 번째 질문은 조금 더 복잡합니다.

따라서 이것은 현재 시험판이지만 모든 일반적인 문제는 사용자가 새로운 속성 (또는 문제의 항목 모음)으로 사용자를 확장하는 것입니다.

기본적으로 IdentityModelModels 폴더 아래에 파일 이 작성됩니다 (작성 당시). 거기에는 몇 개의 수업이 있습니다. ApplicationUser그리고 ApplicationDbContext. 컬렉션을 추가하려면 클래스가 Entity Framework와 함께 사용하는 일반 클래스 인 것처럼 클래스 Items를 수정해야합니다 ApplicationUser. 실제로, 당신이 후드를 간단히 살펴보면 모든 신원 관련 클래스 (사용자, 역할 등 ...)가 적절한 데이터 주석이있는 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 core 2.2에서는 HttpContext.User.Identity.Name을 사용합니다. 그것은 나를 위해 일했다.


이것이 내가 AspNetUser ID를 얻어 내 홈페이지에 표시 한 방법입니다

HomeController Index () 메소드에 다음 코드를 배치했습니다.

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

In the view page just call

ViewBag.userId 

Run the project and you will be able to see your userId

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

반응형