Solution for RunWithElevatedPrivileges not working:
When we use the ElevatedPrivileges then we need to use the following syntax
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//Code to run with Elevated Previliges
}
Here Code will not run with elevated previliges, because we need to create web object with elevated previliges.
Following Syntax will work for this case:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using( SPSite site = new SPSite(SPContext.Current.Site.ID))
{
using (SPWeb web = site.OpenWeb())
{
//Code to run with Elevated Previliges
}
}
});
Here SPsite object is created with Elevated Privileges, so code will run as per the requirement.
The meaning of running code with elevated privileges means it runs with the application pool identity. By default it will be System Account.
If we need to run the code with Elevated Privileges but not with application pool identity then we should use the following syntax:
string ServiceAccount=”CompleteUserID”; // User id in variable
var user = SPContext.Current.Web.AllUsers[ServiceAccount]; //Creating User Token with user id
var superToken = user.UserToken;
using (var spSite = new SPSite(SPContext.Current.Web.Url, superToken))
{
using (SPWeb web3 = spSite.OpenWeb())
{
}
});
Here ServiceAccount is the string variable to assign userid. And we will use the same user token to create SPsite object.
Please let me know for any other clarification.
No comments:
Post a Comment