2012-01-17 45 views

回答

52

你可以做這樣的事情:

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

你需要添加對System.DirectoryServices.AccountManagement組件的引用。

您可以添加一個剃刀幫手,像這樣:

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

如果indend從視圖這樣做,而不是控制,你需要添加一個裝配參考你的web.config,以及:

<add assembly="System.DirectoryServices.AccountManagement" /> 

根據configuration/system.web/assemblies加上那個。

+0

我只是想實現剃刀助手和<添加組件=「System.DirectoryServices.AccountManagement」 />拋出一個錯誤(找不到引用),但使用System.DirectoryServices.AccountManagement從C#文件工作,該dll包含在項目引用,任何想法? – 2012-01-18 01:28:15

+4

想通了,必須將DLL的「copy local」屬性設置爲true。 :) – 2012-01-18 01:35:24

+3

對於MVC4,web.config在'configuration/system.web/pages/namespaces'中需要'''。 – Lawtonfogle 2014-08-22 18:18:37

7

另一種選擇,而不需要一個幫手......你可以只申報情況和主要你需要利用這些值,然後利用它像一個標準的輸出之前...

@{ // anywhere before needed in cshtml file or view 
    var context = new PrincipalContext(ContextType.Domain); 
    var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name); 
} 

然後內的任何地方文檔,只需調用每個變量需要:

@principal.GivenName // first name 
@principal.Surname // last name 
+1

這與前面的答案基本相同,但不需要幫手是我的看法的一個優點,所以我更喜歡你的答案。 :) – 2014-09-25 18:00:46

1

如果你已經升級到Identity 2和使用要求,那麼這種信息的將是一個要求。嘗試創建一個擴展方法:

public static string GetFullName(this IIdentity id) 
{ 
    var claimsIdentity = id as ClaimsIdentity; 

    return claimsIdentity == null 
     ? id.Name 
     : string.Format("{0} {1}", 
      claimsIdentity.FindFirst(ClaimTypes.GivenName).Value, 
      claimsIdentity.FindFirst(ClaimTypes.Surname).Value); 
} 

然後你就可以在這樣的視圖中使用它:

@Html.ActionLink("Hello " + User.Identity.GetFullName() + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" }) 
+0

Hi @Sinaesthetic。你能否通過一些鏈接來解釋Scratch的ClaimsIdentity? – Kulkarni 2015-11-13 06:38:36

+0

https://msdn.microsoft.com/en-us/library/ff423674.aspx – Sinaesthetic 2015-11-16 16:15:02

1

如果你有多個控制器,然後使用@vcsjones的方法可能是不好受。 因此,我建議創建TIdentity的擴展方法。

public static string GetFullName(this IIdentity id) 
    { 
     if (id == null) return null; 

     using (var context = new PrincipalContext(ContextType.Domain)) 
     { 
      var userPrincipal = UserPrincipal.FindByIdentity(context, id.Name); 
      return userPrincipal != null ? $"{userPrincipal.GivenName} {userPrincipal.Surname}" : null; 
     } 
    } 

然後你就可以在你的視圖中使用它:

<p>Hello, @User.Identity.GetFullName()!</p> 
相關問題