From:http://www.cnblogs.com/BruceLee521/
开始以为要构建
WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
GenericPrincipal genericPrincipal =new GenericPrincipal(genericIdentity, roles);
然后把HttpContext.Current.User 置成上面构造的。但发现在打开个人站点时出错。
然后修改个人站点C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\SiteTemplates\SPSPERS\default.aspx
加入
username:<%=HttpContext.Current.User.Identity.Name%>:
authen:<%=HttpContext.Current.User.Identity.AuthenticationType%>
authe:<%=HttpContext.Current.User.GetType().ToString()%>
identity:<%=HttpContext.Current.User.Identity.GetType().ToString()%>
运行发现页面输出
helloWORLD:sunsheng: authen:Forms authe:System.Web.Security.RolePrincipal identity:System.Web.Security.FormsIdentity
才知道构造用户错误,应该构造
System.Web.Security.RolePrincipal
System.Web.Security.FormsIdentity
public class MOSSFBAImpersonate
{
//code sample by Ric
//================
// MOSSFBAImpersonate mossFBAImpersonate = new MOSSFBAImpersonate(ConfigurationManager.AppSettings.Get("RoleProviderName"));
// FBAIP.Impersonate([roleProvidernameFromWebconfig],[impersonatingUserName]);
// //to do you work here....
// FBAIP.Revoke();
//================
#region public functions
public MOSSFBAImpersonate(string roleProviderName)
{
m_rolePrincipal = (IPrincipal)HttpContext.Current.User;
m_roleProvider = roleProviderName;
if (null == m_roleProvider)
throw (new Exception("MOSSFBAImpersonate::roleProviderName is null!"));
}
public void Impersonate(string userName)
{
HttpContext.Current.User = this.CreateHttpUser(m_roleProvider, userName);
}
public void Revoke()
{
if (null != m_rolePrincipal)
HttpContext.Current.User = (IPrincipal)m_rolePrincipal;
}
#endregion
#region private region
private object m_rolePrincipal = null;
private string m_roleProvider = null;
private RolePrincipal CreateHttpUser(string roleProviderName, string userName)
{
GenericIdentity genericIdentity = new GenericIdentity(userName, "Forms");
return new RolePrincipal(roleProviderName, genericIdentity);
}
#endregion
}
来进行模拟用户
得到个人站点的代码可以如下:
public SPWeb GetPersonalWeb(string strAccount, string strPersonalSiteHost)
{
SPWeb myWeb = null;
SPSite spPersonalSite = null;
MOSSFBAImpersonate mossFBAImpersonate = new MOSSFBAImpersonate(ConfigurationManager.AppSettings.Get("RoleProviderName"));
try
{
mossFBAImpersonate.Impersonate(strAccount);
spPersonalSite = new SPSite(strPersonalSiteHost);
myWeb = spPersonalSite.RootWeb;
mossFBAImpersonate.Revoke();
}
catch (System.Threading.ThreadAbortException thex)
{
throw thex;
}
catch (Exception ex)
{
throw ex;
}
finally
{
//myWeb.Dispose(); //which will be disposed by outside caller.
spPersonalSite.Dispose();
}
return myWeb;
}