SPSecurity.RunWithElevatedPrivileges(delegate()
{
// implementation details omitted
});
可以提升代碼的運行權限,實現模擬管理員身份的功能。
在RunWithElevatedPrivileges中不要使用 SPContext.Current.Web,SPContext.Current.Site,SPControl.GetContextWeb(HttpContext.Current) 之類的根據當前上下文得到當前的Web或者Site,根據這些方法得到的所有對象(包括從根據這些對象得到的List,ListItem等等對象)都是以 當前網站登錄用戶權限運作的,即使是在RunWithElevatedPrivileges其運作權限也不會是管理員。
所以,如果要真正讓在RunWithElevatedPrivileges中的代碼以管理員權限正常運作的話,必須重新初始化相應的對象,比如:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite mySite = new SPSite(SPContext.Current.Site.Url))
{
Response.Write(mySite.RootWeb.CurrentUser.LoginName);
}
});
以上mySite.RootWeb.CurrentUser.LoginName返回的是管理員的登錄帳號。
但是如果按之前所說使用SPContext:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
Response.Write(SPContext.Current.Web.CurrentUser.LoginName);
});
這時候即使在提升權限的范圍內運行,得到的也是當前網站登錄帳戶名,而不是管理員登錄帳號
































