Tuesday, April 7, 2009

When to use AllowUnsafeUpdates, ValidateFormDigest() or else

For scenarios in which your code is processing a POST request, ValidateFormDigest() will, behind the scenes, set AllowUnsafeUpdates to true.

But some scenarios (e.g. web services) are not a POST request, therefore ValidateFormDigest() will fail.

So, here's a simple decision tree to help:

HttpContext.Current is null => Do nothing, no need to set AllowUnsafeUpdates to true nor to call ValidateFormDigest() because update will be carried out (e.g. code being called from an .exe from a cmd prompt)

HttpContext.Current is NOT null
- SPContext.Current is null => Need to set AllowUnsafeUpdates to true (e.g. web service)
- SPContext.Current is NOT null => Call ValidateFormDigest() (e.g. POST request processing)

No comments: