What you need to know about AllowUnsafeUpdates (Part 1) [Reproduced]

Source: Internet
Author: User

Original article address: SharePoint Internals-Hristo Pavlov's Blog

I am not good at English. Read the original article! Haha

In short here is how to dealAllowUnsafeUpdates:

1) Don't update SharePoint objects from your code behind on GET requests as if you do so your code will be exploitable via a cross-site scripting. if you understand the consequences of doing this and still want to do it then read below about how to useAllowUnsafeUpdatesProperty.

2) If your code is processing a POST request then make sure you call SPUtility. validateFormDigest () before you do anything else. this will ensure that the post request is validated (that it is not a cross-site scripting attack) and after that you will not have to worry aboutAllowUnsafeUpdates, Because its default value will be"True"After the form digest is validated. To find out more about this read the second part of this article.

The Microsoft idea behind introducingAllowUnsafeUpdatesProperty is to protect YOU from cross-site scripting attacks. the way this works is that if your application is running in an HTTPContext (I. e. it's a web part for instance) and the request is a GET request then SharePoint will refuse to do any changes unless the valueAllowUnsafeUpdatesIs set to true and by default it will be false for GET requests. If you try to do any updates to lists, webs or any SharePoint objects that requireSPSiteTo be created first, and if you don't setAllowUnsafeUpdatesTo true you will get this exception:

System. exception: Microsoft. sharePoint. SPException: The security validation for this page is invalid. click Back in your Web browser, refresh the page, and try your operation again. -> System. runtime. interopServices. COMException (0x8102006D): The security validation for this page is invalid. click Back in your Web browser, refresh the page, and try your operation again.

It is important to understand that if you are writing a class library for example, your code will behave differently when called from a web application and when called from a rich client. Actually ifHTTPContext. CurrentIs null thenAllowSafeUpdatesWill be always true. This is the case in rich clients where no cross-scripting is possible as there are simply no web requests.

Usually when you create your ownSPSiteOrSPWebObjects, I. e. when you are not getting them fromSPContext(Such as SPContext. web), and when you try to update anything such as web or list properties, list items metadata etc, you may get the exception listed above. this is a clear indication thatAllowUnsafeUpdatesOf the SPWeb is false and this is preventing you from doing the update. This problem is resolved easily by settingAllowUnsafeUpdatesOf the parent web object to true. Still sometimes even after you have done this you may still be getting the same error. This is typically caused by one of the following reasons:

A) You have setAllowUnsafeUpdateTo true for the wrong SPWeb

You have to be careful because sometimesParentWebOf an object is not the same instance of the web you have retrieved the object from. For example when you goInitialWeb. Lists [listId]You wowould perform CT that the returned list's ParentWeb instance is the same as youInitialWeb. However this is not the case. So if somewhere later in your code you goList. ParentWeb. UpdateSomething ()This will not work because you have never setAllowUnsafeUpdatesPropertyList. ParentWeb. You have set it for yourInitialWebBut even that this is the same web as the list's parent web both are different instances. usually you see the error and then you go and investigate in Reflector whether this is the same instance or not. alternatively you cocould use another more generic and clever way to deal with almost any similar situation described in the following post:

Http://community.bamboosolutions.com/blogs/bambooteamblog/archive/2008/05/15/when-allowunsafeupdates-doesn-t-work.aspx

The author suggests that you can setHttpContent. CurrentTo null before you do your updates and then reassign its initial preserved value when done. this will work great but remember to set the HTTPContent to null as early as possible. in the post above probably SharePoint usesSite. RootWebTo do the updates to the site scoped features and the RootWeb'sAllowUnsafeUpdatesHasn' t been set to true explicitly.

B)AllowUnsafeUpdatesGets reset to false sometimes after you have set it to true

If we have a look at how the property is managed it turns out that it is stored in the request object associated with every SPWeb (which is actually a COM object) [using pointpermission (SecurityAction. demand, UnsafeSaveOnGet = true)]

Private void SetAllowUnsafeUpdates (bool allowUnsafeUpdates)

{

This. Request. SetIgnoreCanary (allowUnsafeUpdates );

}

This actually means that every time the request is reset, the property will be also reset to its default value.M_RequestMember is modified when a new web is created, when the web is disposed or whenSPWeb. Invalidate ()Method is called.

Internal void Invalidate ()

{

If (this. m_Request! = Null)

{

If (this. m_RequestOwnedByThisWeb)

{

SPRequestManager. Release (this. m_Request );

}

This. m_Request = null;

}

This. m_bInited = false;

This. m_bPublicPropertiesInited = false;

This. m_Url = null;

}

So any operation that CILSSPWeb. Invalidate ()Will resetAllowUnsafeUpdateTo its default value. and for code running under HTTPContext, I. e. web applications, this default value for a GET request will be false. I 've looked up for you all legitimate cases for which Invalidate () is being called by the SharePoint object model. these cases are:

1) WhenNameOrServerRelativeUrlProperties ofSPWebAre changed and thenUpdate ()Is called. in this case the AllowUnsafeUpdate is reset because with the change of these properties the URL of the web will change and logically the request object will change as it will now point to a different URL.

2) When any object that implementsISecurable(Those are SPWeb, SPList and SPListItem) breaks or reverts their role definition inheritance. This means every time you callSPRoleDefinitionCollection. BreakInheritance (),BreakRoleInheritance (),ResetRoleInheritance ()Or set the valueHasUniquePermTheAllowUnsafeUpdatesProperty of the parent web will reset to its default value and you may need to set it back to true in order to do further updates to the same objects.

3) In advance cases when an exception is caught by the SharePoint object model when you try to retrieve any sort of dataAllowUnsafeUpdatesOf the parent web will be reset to false as a precaution to protect against potential exploits. in those cases however the objects will be in unknown state anyway after the request has been reset and the exception is re-thrown so they are of no practical interest.

And finally it is also good to mention that you may get another related exception when trying to update your SharePoint objects and that is:

System. Exception: Microsoft. SharePoint. SPException: Cannot complete this action. Please try again.-> System. Runtime. InteropServices. COMException (0 × 80004005): Cannot complete this action.

This usually happens when some updates have been made to an object (usually SPSite, SPWeb or SPList) that may be clashing with your changes and SharePoint refuses to do the update. to recover from this situation you simply need to create fresh copies of the SPSite and the SPWeb objects and do the updates on the objects retrieved from the fresh copies. and of course don't forget to setAllowUnsafeUpdatesTo true for the freshly created SPWeb if required.

Technorati tags: Sharepoint, moss

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.