When & why I need to use web.AllowUnsafeUpdates = true, and why it is false by default:
web.AllowUnsafeUpdates = true;
//Update Item
web.AllowUnsafeUpdates = false;
When & why I need to use web.AllowUnsafeUpdates = true, and why it is false by default:
web.AllowUnsafeUpdates = true;
//Update Item
web.AllowUnsafeUpdates = false;
For reasons of security, by default, Microsoft SharePoint Foundation does not allow you to make posts from a Web application to modify the contents of the database unless you include security validation on the page making the request. You can update data for a single site or for a site collection by adding a page directive and a FormDigest control to the page that makes the request.
To GET the content from the content DB, we need to set the AllowUnsafeUpdates = true. To POST the content to the content DB, not require to set the AllowUnsafeUpdates = true. why means because of "FormDigest" control placed in every master page.
When/where/why use "AllowUnsafeUpdates" in SharePoint?
WHY --> to prevent your code from cross site scripting.
If you are updating content DB using a POST request then you should use SPUtility.ValidateFormDigest() to validate the current request and after that you will not have to worry about AllowUnsafeUpdates, because its default value will be “true” after the form digest is validated. The Microsoft idea behind introducing the AllowUnsafeUpdates property is to protect you from cross-site scripting attacks.
If you are using GET request to update the sharepoint objects then it will throw an exception System.Exception: Microsoft.SharePoint.SPException bcoz your code will be exploitable via a cross-site scripting. To prevent this CSS you have to set AllowUnsafeUpdates to true and after changes make it to false or whatever the previous value.
Also If the HTTPContext.Current is null then AllowSafeUpdates will be always true. This is the case in rich clients where no cross-scripting is possible as there are simply no web requests.