有的时候用户会提出一些需求,例如想在一个网站中一个比较显眼的位置修改自己的信息,这时我们往往需要做一个WebPart来给用户修改,这个WebPart的主要功能就是获取当前用户的UserProfile信息,然后提供一些可以编辑的信息给用户自己编辑并保存回UserProfile,怎么读取UserProfile呢?读取UserProfile需要提升用户权限,主要代码如下:
![ContractedBlock.gif](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 SPSecurity.RunWithElevatedPrivileges(delegate 2 { 3 using (SPSite mySite = new SPSite(SPContext.Current.Site.ID)) 4 { 5 6 SPServiceContext myContext = SPServiceContext.GetContext(mySite); 7 8 UserProfileManager myProfile = new UserProfileManager(myContext); 9 UserProfile user = myProfile.GetUserProfile(userName); 10 if (user != null) 11 { 12 string property1 = user["UserProfileProperty"].Value; 13 } 14 } 15 });
UserProfileProperty需要换成用户配置文件中的具体属性,username是用户的LoginName,因为代码有提升用户权限,所以取当前的User不能在这段代码中间取,需要在外部将当前用户的LoginName取好了拿进来用,不然就是取的系统帐户。
上面的代码需要用到3个命名空间:
using Microsoft.SharePoint;
using Microsoft.Office.Server;using Microsoft.Office.Server.UserProfiles;