private void yourFunction()
{
SPSite site = SPContext.Current.Site;
SPWeb web = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite ElevatedSite = new SPSite(site.ID))
{
using (SPWeb ElevatedWeb = ElevatedSite.OpenWeb(web.ID))
{
srList = ElevatedWeb.Lists["Service Requests"];
SPListItem newItem = srList.Items.Add();
// Do stuff to create the list item
ElevatedWeb.AllowUnsafeUpdates = true;
newItem.Update();
Guid temp = newItem.UniqueId;
newItem["Link"] = "<DIV><a href=\"https://YourSite.com/_layouts/custom/ViewSR.aspx?ID=" + temp.ToString("d") + "\">View SR</a></DIV>";
newItem.Update();
ElevatedWeb.AllowUnsafeUpdates = false;
}
}
});
}
{
SPSite site = SPContext.Current.Site;
SPWeb web = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite ElevatedSite = new SPSite(site.ID))
{
using (SPWeb ElevatedWeb = ElevatedSite.OpenWeb(web.ID))
{
srList = ElevatedWeb.Lists["Service Requests"];
SPListItem newItem = srList.Items.Add();
// Do stuff to create the list item
ElevatedWeb.AllowUnsafeUpdates = true;
newItem.Update();
Guid temp = newItem.UniqueId;
newItem["Link"] = "<DIV><a href=\"https://YourSite.com/_layouts/custom/ViewSR.aspx?ID=" + temp.ToString("d") + "\">View SR</a></DIV>";
newItem.Update();
ElevatedWeb.AllowUnsafeUpdates = false;
}
}
});
}
Best Practices:
Correct Usage Sample:
SPSecurity.RunWithElevatedPrivileges(delegate() { //New SPSite object. using (SPSite site = new SPSite(web.Site.ID)) { //Do things by assuming the permission of the "system account". } });
Faulty Usage:
//SPSite Object created outside the RWEP Method SPSite site = new SPSite("siteURL"); SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPWeb web = site.OpenWeb()) { string user = web.CurrentUser.Name; //Operations that need high level access. } });
No comments:
Post a Comment