如何AllowUnsafeUpdates

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.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值