Guid SiteId = SPContext.Current.Site.ID;
Guid WebId = SPContext.Current.Web.ID;SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite ElevatedSite = new SPSite(SiteId))
{
using (SPWeb ElevatedWeb = ElevatedSite.OpenWeb(WebId))
{
//Code to change permissions
}
}
});
Using this code, at the moment you execute the sentences to change the permissions, you get an error like: "The security validation for this page is invalid". The way to solve this error is to set the AllowUnsafeUpdates property to true for the SPWeb object and validate the form digest control used in the current request. Hence the code snippet will look like this:
Guid SiteId = SPContext.Current.Site.ID;
Guid WebId = SPContext.Current.Web.ID;SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite ElevatedSite = new SPSite(SiteId))
{
using (SPWeb ElevatedWeb = ElevatedSite.OpenWeb(WebId))
{
ElevatedWeb.AllowUnsafeUpdates = true;
ElevatedWeb.Update();
SPUtility.ValidateFormDigest();//Code to change permissions
ElevatedWeb.AllowUnsafeUpdates = false;
}
}
});
And finally the code to change the permissions would look some thing like this:
listItem.BreakRoleInheritance(false);
SPRoleAssignment role = new SPRoleAssignment(SPContext.Current.Web.EnsureUser("SOMEUSERorGROUP"));
role.RoleDefinitionBindings.Add(ElevatedWeb.RoleDefinitions.GetByType(SPRoleType.Contributor)); //Or any other SPRoleType
listItem.RoleAssignments.Add(role);
listItem.Update();
This worked for me. Hope it helps!
0 comments:
Post a Comment