Monday, April 6, 2009

SPSecurity.RunWithElevatedPrivileges() throws InvalidOperationException, "Operation is not valid due to the current state of the object."

There are several reasons for this to happen.

1) HttpContext.Current.User == null
2) code running under impersonation.

If it's 2), here's one recipe, save HttpContext, set it to null, restore it back:

            HttpContext prev = HttpContext.Current;
HttpContext.Current = null;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
...
});
}
finally
{
HttpContext.Current = prev;
}

No comments: