2017-07-11 44 views
0

我是新來的asp.net mvc,需要在_Layout視圖中獲取用戶的名和姓。如何從Windows驗證中獲取姓氏和名字

我通過這條線有沒有域名數據的用戶名

@Request.LogonUserIdentity.Name.Substring(Request.LogonUserIdentity.Name.LastIndexOf(@"\") + 1) 

我看到了一個解決方案,它看起來像 -

添加引用System.DirectoryServices.AccountManagement

using (var context = new PrincipalContext(ContextType.Domain)) 
{ 
    var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name); 
    var firstName = principal.GivenName; 
    var lastName = principal.Surname; 
} 

添加剃刀幫手像這樣:

@helper AccountName() 
    { 
     using (var context = new PrincipalContext(ContextType.Domain)) 
    { 
     var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name); 
     @principal.GivenName @principal.Surname 
    } 
} 

但_Layout.cshtml沒有控制器,如果我直接將它放在剃鬚刀中也不起作用。

任何幫助將appriciated!

+0

怎麼樣使用會話... –

+0

但在哪裏邏輯witten?我需要在_Layout.cshtml中顯示它.. 以及如何從會話中獲取名和姓?據我所知,我可以獲得密鑰\用戶名\計算機名稱... –

+0

登錄後,您可以在會話變量中存儲名和姓。我的意思是在登錄操作方法。然後你可以訪問你的_Layout頁面。 –

回答

0

OK,所以很多剃刀是如何工作的我發現在_Layout.cshtml的解決方案, 思考之後 -

<head> 
    @using System.DirectoryServices.AccountManagement; 
</head> 

<body> 
    @{ 
     var context = new PrincipalContext(ContextType.Domain); 
     var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name); 
     var firstName = principal.GivenName; 
     var lastName = principal.Surname; 
    } 
<p class="navbar-brand"> @firstName @lastName </p> 
</body> 

希望這會有所幫助。