InvalidProgramException 在 Microsoft.Office.Server.UserProfiles.UserProfileManager 上抛出

InvalidProgramException throws on Microsoft.Office.Server.UserProfiles.UserProfileManager

我正在制作一个需要使用以下代码从活动目录中获取当前用户信息的 Web 部件:

protected void fetchUserInfo()
{
    System.Security.PermissionSet ps = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.Unrestricted);
    ps.Assert();

    Microsoft.SharePoint.SPServiceContext serviceContext = Microsoft.SharePoint.SPServiceContext.Current;
    UserProfileManager upm = new Microsoft.Office.Server.UserProfiles.UserProfileManager(serviceContext);
    ProfileSubtypePropertyManager pspm = upm.DefaultProfileSubtypeProperties;
    string userName = SPContext.Current.Web.CurrentUser.LoginName;
    UserProfile profile = upm.GetUserProfile(userName);

    foreach (ProfileSubtypeProperty prop in pspm.PropertiesWithSection)
    {
    }
}

但是 InvalidProgramException 在行 ProfileSubtypePropertyManager pspm = upm.DefaultProfileSubtypeProperties;

上抛出

错误信息是:

Common Language Runtime detected an invalid program.

我试过谷歌搜索 Common Language Runtime detected an invalid program. sharepointUserProfileManager但是没有太多信息。

可能是什么问题?


刚才看到异常流到UserProfileManager,所以SPServiceContext是无效的,当我查看serviceContext上的属性 SiteSubscriptionId时,我发现它是00000000-0000-0000-0000-000000000000

那么这是什么意思呢?有没有其他方法可以从 sharepoint 获取当前用户信息?

最后,我改变了主意,使用 UserPrincipal 获取用户信息:

    PrincipalContext _principalcontext = GetPrincipalContext();
    UserPrincipal _user = UserPrincipal.FindByIdentity(_principalcontext, IdentityType.SamAccountName, UID);

    if (_user != null)
    {
        DirectoryEntry directoryEntry = _user.GetUnderlyingObject() as DirectoryEntry;
        //Property is here;
    }