source

ASP.NET MVC에서 현재 사용자를 가져오는 방법

factcode 2023. 5. 24. 22:28
반응형

ASP.NET MVC에서 현재 사용자를 가져오는 방법

양식 모델에서 현재 로그인한 사용자를 얻는 방법은 다음과 같습니다.

Page.CurrentUser

ASP.NET MVC의 컨트롤러 클래스 내에서 현재 사용자를 가져오려면 어떻게 해야 합니까?

할 에는 사용합니다.User컨트롤러 속성입니다.보기에서 필요하다면 특별히 필요한 것을 입력하겠습니다.ViewData아니면 그냥 사용자에게 전화할 수도 있습니다. 제 생각에 그것은 의 속성입니다.ViewPage.

나는 그것을 발견했습니다.User즉, 작동합니다.User.Identity.Name또는User.IsInRole("Administrator").

ㅠㅠHttpContext.Current.User.

공용 공유 속성 현재() 시스템입니다.입니다.HttpContext
시스템의 구성원.Web.HttpContext

요약:.
시스템을 가져오거나 설정합니다.현재 HTTP 요청에 대한 Web.HttpContext 입니다.

반환 값:
시스템.현재 "" HTTP "" 입니다.HttpContext

다음과 같이 ASP.NET MVC4에서 사용자의 이름을 가져올 수 있습니다.

System.Web.HttpContext.Current.User.Identity.Name

저는 이것이 정말 오래되었다는 것을 알고 있지만, 저는 이제 막 ASP.NET MVC를 시작했습니다. 그래서 저는 제 2센트를 다음에 넣으려고 생각했습니다.

  • Request.IsAuthenticated사용자가 인증되었는지 여부를 알려줍니다.
  • Page.User.Identity로그인한 사용자의 ID를 제공합니다.

사용자:

Membership.GetUser().UserName

이것이 ASP.NET MVC에서 작동할지 확신할 수 없지만, 시도해 볼 가치가 있습니다 :)

이름에 하기: 사용자이로그하는중인름에중▁getting는.System.Web.HttpContext.Current.User.Identity.Name

사용자 이름:

User.Identity.Name

그러나 ID만 필요한 경우 다음을 사용할 수 있습니다.

using Microsoft.AspNet.Identity;

따라서 사용자 ID를 직접 가져올 수 있습니다.

User.Identity.GetUserId();

필터링 목적으로 컨트롤러의 ASP.NET MVC 4에 내장된 단순 인증을 사용하여 생성된 사용자 ID를 참조하려면(데이터베이스 우선 및 Entity Framework 5를 사용하여 코드 우선 바인딩을 생성하고 테이블이 사용자에게 외부 키로 구성되어 있는 경우 유용합니다).ID 사용), 사용할 수 있습니다.

WebSecurity.CurrentUserId

사용 설명을 추가하면

using System.Web.Security;

다음 코드를 사용하여 ASP.Net MVC에 현재 로그인된 사용자를 가져올 수 있습니다.

var user= System.Web.HttpContext.Current.User.Identity.GetUserName();

또한.

var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; //will give 'Domain//UserName'

Environment.UserName - Will Display format : 'Username'

가 될 수 .
페이지 사용.사용자. 신원.MVC3MVC3에

당신은 그저 필요합니다.User.Identity.Name.

사용하다System.Security.Principal.WindowsIdentity.GetCurrent().Name.

현재 로그인한 Windows 사용자를 가져옵니다.

ASP.NET MVC 3에서는 현재 요청에 대한 사용자를 반환하는 사용자를 사용할 수 있습니다.

로그인 페이지 내에 있는 경우 LoginUser_Logged에서예를 들어 Current와 같은 이벤트입니다.사용자. 신원.이름은 빈 값을 반환하므로 LoginControlName을 사용해야 합니다.사용자 이름 속성.

MembershipUser u = Membership.GetUser(LoginUser.UserName);

다음 코드를 사용할 수 있습니다.

Request.LogonUserIdentity.Name;
IPrincipal currentUser = HttpContext.Current.User;
bool writeEnable = currentUser.IsInRole("Administrator") ||
        ...
                   currentUser.IsInRole("Operator");
var ticket = FormsAuthentication.Decrypt(
                    HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value);

if (ticket.Expired)
{
    throw new InvalidOperationException("Ticket expired.");
}

IPrincipal user =  (System.Security.Principal.IPrincipal) new RolePrincipal(new FormsIdentity(ticket));

인트라넷의 Active Directory에서 작업하는 경우 다음과 같은 팁이 있습니다.

(윈도우즈 서버 2012)

웹 서버에서 AD와 대화하는 모든 것을 실행하려면 많은 변화와 인내가 필요합니다.로컬 IIS/IIS Express가 아닌 웹 서버에서 실행되는 경우 AppPool의 ID에서 실행되므로 사이트를 방문하는 사용자를 가장하도록 설정해야 합니다.

ASP.NET MVC 응용 프로그램이 네트워크 내부의 웹 서버에서 실행 중일 때 활성화된 디렉토리에서 현재 로그인한 사용자를 가져오는 방법:

// Find currently logged in user
UserPrincipal adUser = null;
using (HostingEnvironment.Impersonate())
{
    var userContext = System.Web.HttpContext.Current.User.Identity;
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings["AllowedDomain"], null,
                                                ContextOptions.Negotiate | ContextOptions.SecureSocketLayer);
    adUser = UserPrincipal.FindByIdentity(ctx, userContext.Name);
}
//Then work with 'adUser' from here...

AD 정보를 가져오기 위한 호스팅 환경으로 사용할 수 있도록 다음의 '액티브 디렉터리 컨텍스트'와 관련된 모든 통화를 정리해야 합니다.

using (HostingEnvironment.Impersonate()){ ... }

당신은 또한 가지고 있어야 합니다.impersonateweb.config에서 true로 설정:

<system.web>
    <identity impersonate="true" />

web.config:에서 윈도우즈 인증이 있어야 합니다.

<authentication mode="Windows" />

Asp.net Mvc Identity 2에서 현재 사용자 이름을 얻을 수 있는 방법은 다음과 같습니다.

var username = System.Web.HttpContext.Current.User.Identity.Name;

IIS 관리자의 인증에서 사용 안 함: 1) 익명 인증 2) 양식 인증

그런 다음 컨트롤러에 다음을 추가하여 서버 배포와 비교한 테스트를 처리합니다.

string sUserName = null;
string url = Request.Url.ToString();

if (url.Contains("localhost"))
  sUserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
else
  sUserName = User.Identity.Name;

만약 누군가가 여전히 이것을 읽고 있다면, 내가 사용한 cshtml 파일에 접근하기 위해 다음과 같은 방법으로.

<li>Hello @User.Identity.Name</li>

언급URL : https://stackoverflow.com/questions/263486/how-to-get-the-current-user-in-asp-net-mvc

반응형