August 28, 2007

MOSS: SPLimitedWebPartManager.SaveChanges throws security exception

Problem:
When modifying Web Part properties programmatically and trying to save changes, an exception is thrown saying that "Security validation for this page is invalid." You have also set the AllowUnsafeUpdates to true on the current web.

Something like this:
private void SetWebPartAudience(string webUrl)
{
    SPWeb tempWeb = null;
 
    try
    {
        tempWeb = new SPSite("http://mysite/myweb").OpenWeb();                
 
        SPLimitedWebPartManager wm = page.GetLimitedWebPartManager("Pages/default.aspx", 
            System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
 
        foreach (System.Web.UI.WebControls.WebParts.WebPart wp in wm.WebParts)
        {
            if (wp.GetType().Equals(typeof(KPIListWebPart)))
            {
                wp.AuthorizationFilter = ";;;;" + "Internal Users";
 
                tempWeb.AllowUnsafeUpdates = true;
                wm.SaveChanges(wp);
                tempWeb.AllowUnsafeUpdates = false;
 
                break;
            }
        }
    }
    catch (Exception e)
    {
    }
    finally
    {
        if (tempWeb != null)
        {
            tempWeb.Dispose();
        }
    } 
}

Solution:
Set AllowUnsafeUpdates on the SPLimitedWebPartManager's Web object like this:

wm.Web.AllowUnsafeUpdates = true;
wm.SaveChanges(wp);
wm.Web.AllowUnsafeUpdates = false;

1 comment:

  1. This absolutley was my problem and the solution posted works as stated.

    Thank you

    ReplyDelete