AllowUnsafeUpdates的定义
根据msdn的解释,当在SharePoint 页面HttpContext上下文中通过GET请求更新SharePoint contentDB时,为了允许更新数据库或者避免安全验证,"AllowUnsafeUpdates" 需要设置成true,
否则,会抛The security validation for this page is invalid异常.
该属性默认为false, 微软引入这个属性是为防止受到cross-site scripting 攻击. 但是,某些情况下, 可能需要更新一些不安全的数据, 这时候可以把它置成false
什么时候使用
在SharePoint 页面HttpContext上下文中通过GET请求更新SharePoint contentDB时
什么时候不需要使用
在一个Console Application, Class Library... ,在这些工程中,HTTPContext.Current = null, AllowUnsafeUpdates默认都为true, 所以不需要设置这个属性.
AllowUnsafeUpdates注意事项:
. 在HTTPContext 上下文中使用, 且操作是Get请求(即页面不跳转-Post) , POST 请求不需要这个属性,因为 FormDigest控件的存在, 使用完后置回成false(安全考虑)
. 但有打破继承的操后后,该属性会重置成默认值-false, 所以后续如果有更新操作需要重新置成true.
Bad piece of code:
SPList sharedPictures = curWeb.Lists["Shared Pictures"];
sharedPictures.Title = "My Pictures";
curWeb.AllowUnsafeUpdates = true; //--> no help!
sharedPictures.BreakRoleInheritance(true);
ReducePermissonsOnLibrary(sharedPictures); //---> crash!
Working piece of code:
SPList sharedPictures = curWeb.Lists["Shared Pictures"];
sharedPictures.Title = "My Pictures";
sharedPictures.BreakRoleInheritance(true);
CurWeb.AllowUnsafeUpdates = true; //BreakRoleInheritance set AllowUnsafeUpdates back to false!
ReducePermissonsOnLibrary(sharedPictures);
. 该属性置成true后,如果后续操作抛异常, 在catch里面该属性也会重置成默认值 -false, 需要注意.
SPWeb web = ...;
try
{
web.AllowUnsafeUpdates = true;
throw new Exception("Something went really wrong underway !");
}
catch (Exception ex)
{
// At this point the web.AllowUnsafeUpdates is false. Before we can update the item we will need to set it to true !
web.AllowUnsafeUpdates = true;
SPListItem errorItem = web.Lists["ErrorLog"].Items.Add();
errorItem["Title"] = "Web.Title update failed";
errorItem["Description"] = ex.ToString();
errorItem.Update();
}
. 当一个页面继承WebPartPage类后,不需要再使用AllowUnsafeUpdates.