문제

양식 모델에서는 현재 로그인 한 사용자를 다음과 같이 가져 왔습니다.

Page.CurrentUser

ASP.NET MVC의 컨트롤러 클래스 내에서 현재 사용자를 어떻게 얻습니까?

도움이 되었습니까?

해결책

컨트롤러 내에서 사용자를 가져와야하는 경우 User 컨트롤러의 속성. 당신이보기에서 그것을 필요로한다면, 나는 당신이 구체적으로 필요로하는 것을 채울 것입니다. ViewData, 또는 사용자에게 전화 할 수 있습니다. ViewPage.

다른 팁

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

노력하다 HttpContext.Current.User.

public shared property current () 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를 참조하기 위해 (데이터베이스 우선 및 엔티티 프레임 워크 5를 사용하여 코드 우선 바인딩을 생성하고 테이블을 구조화하는 경우에 도움이됩니다. userID에 대한 외국 키가 사용된다는 것은)

WebSecurity.CurrentUserId

사용 명령문을 추가하면

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에서는 현재 요청에 대해 사용자를 반환하는 사용자를 사용할 수 있습니다.

로그인 페이지에있는 경우 loginuser_loggedin event, current.user.identity.name은 빈 값을 반환하므로 yourLoginControlName.username 속성을 사용해야합니다.

MembershipUser u = Membership.GetUser(LoginUser.UserName);
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)

웹 서버에서 광고와 관련된 모든 것을 실행하려면 많은 변화와 인내가 필요합니다. 웹 서버에서 실행할 때와 로컬 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...

다음과 같은 'Active Directory Context'와 관련된 통화를 마무리해야하므로 광고 정보를 얻기 위해 호스팅 환경 역할을합니다.

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

당신도 가지고 있어야합니다 impersonate web.config에서 true로 설정하십시오.

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

web.config에서 Windows 인증이 있어야합니다.

<authentication mode="Windows" />

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

Request.LogonUserIdentity.Name;

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;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top