ASP.NET MVC에서 현재 사용자를 얻는 방법
양식 모델에서는 다음과 같이 현재 로그인 한 사용자를 가져 왔습니다.
Page.CurrentUser
ASP.NET MVC의 컨트롤러 클래스 내에서 현재 사용자를 얻으려면 어떻게해야합니까?
컨트롤러 내에서 사용자를 가져와야하는 경우 User
Controller 속성을 사용하십시오 . 보기에서 필요하면의 특정 항목을 구체적으로 채우 ViewData
거나의 속성이라고 생각할 때 사용자에게 전화 할 수 있습니다 ViewPage
.
그 발견 User
하다, 일을, User.Identity.Name
또는 User.IsInRole("Administrator")
.
시도하십시오 HttpContext.Current.User
.
공용 공유 속성 Current () As System.Web.HttpContext System.Web.HttpContext의
멤버요약 :
현재 HTTP 요청에 대한 System.Web.HttpContext 개체를 가져 오거나 설정합니다.반환 값 :
현재 HTTP 요청에 대한 System.Web.HttpContext
다음과 같이 ASP.NET MVC4에서 사용자 이름을 얻을 수 있습니다.
System.Web.HttpContext.Current.User.Identity.Name
나는 이것이 실제로 오래되었다는 것을 알고 있지만 ASP.NET MVC를 시작하고 있습니다. 따라서 2 센트를 넣을 것이라고 생각했습니다.
Request.IsAuthenticated
사용자 인증 여부를 알려줍니다.Page.User.Identity
로그인 한 사용자의 신원을 알려줍니다.
나는 사용한다:
Membership.GetUser().UserName
이것이 ASP.NET MVC에서 작동하는지 확실하지 않지만 한 번 볼만한 가치가 있습니다. :)
로그인 사용자 이름 : System.Web.HttpContext.Current.User.Identity.Name
필터링 목적으로 컨트롤러에서 ASP.NET MVC 4에 내장 된 간단한 인증을 사용하여 생성 된 사용자 ID를 참조하기 위해 (데이터베이스를 먼저 사용하고 Entity Framework 5를 사용하여 코드 우선 바인딩을 생성하고 테이블을 구성하는 경우 유용합니다. userID에 대한 외래 키를 사용하는 경우)
WebSecurity.CurrentUserId
using 문을 추가하면
using System.Web.Security;
사용자 이름 :
User.Identity.Name
그러나 ID를 가져와야 할 경우 다음을 사용할 수 있습니다.
using Microsoft.AspNet.Identity;
따라서 사용자 ID를 직접 얻을 수 있습니다.
User.Identity.GetUserId();
이 페이지는 당신이 찾고있는 것일 수 있습니다 :
MVC3에서 Page.User.Identity.Name 사용하기
당신은 필요합니다 User.Identity.Name
.
사용하십시오 System.Security.Principal.WindowsIdentity.GetCurrent().Name
.
현재 로그인 한 Windows 사용자가 표시됩니다.
다음 코드를 사용하여 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'
가치있는 것을 위해 ASP.NET MVC 3에서는 현재 요청에 대한 사용자를 반환하는 User를 사용할 수 있습니다.
로그인 페이지 내에있는 경우 예를 들어 LoginUser_LoggedIn 이벤트에서 Current.User.Identity.Name은 빈 값을 반환하므로 yourLoginControlName.UserName 속성을 사용해야합니다.
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에서 작업하는 경우 몇 가지 팁이 있습니다.
(Windows Server 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 정보를 얻기 위해 호스팅 환경으로 작동하도록 다음에서 'Active Directory 컨텍스트'와 관련된 모든 호출을 래핑해야합니다.
using (HostingEnvironment.Impersonate()){ ... }
impersonate
web.config에서 true로 설정 해야합니다 .
<system.web>
<identity impersonate="true" />
web.config에 Windows 인증이 있어야합니다.
<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;
참고 URL : https://stackoverflow.com/questions/263486/how-to-get-the-current-user-in-asp-net-mvc
'IT' 카테고리의 다른 글
C # 프로그램을 50msec 동안 절전 모드로 전환하려면 어떻게합니까? (0) | 2020.03.29 |
---|---|
파이썬에서 파일의 줄을 검색하고 바꾸기 (0) | 2020.03.29 |
의사 요소의 누적 순서를 부모 요소 아래에 설정할 수 있습니까? (0) | 2020.03.29 |
문자열에서 단어 바꾸기-Ruby (0) | 2020.03.29 |
django에서 사용자 IP 주소를 어떻게 얻습니까? (0) | 2020.03.29 |