edcf 发表于 2015-9-27 11:19:50

[SharePoint]如何防止从代码跳到“拒绝访问”页面

  在代码中执行没有权限的操作时,SharePoint平台会抛出“拒绝访问(access denied)”异常,并将用户重定向到_layouts/AccessDenied.aspx页面。即使你尝试使用try...catch...finally来捕获处理这个异常,但是代码会在出错的地方停止继续执行,并且异常并不能被你的代码catch住。

  当发生“拒绝访问”异常时,默认情况下SharePoint平台会自己捕获它,并将用户重定向到_layouts/AccessDenied.aspx页面,以便告诉用户没有权限,可以请求管理员给自己分配权限,或使用一个有权限的用户登陆。
  如果你想在代码中处理这个异常,需要将Microsoft.SharePoint.SPSecurity.CatchAccessDeniedException属性设置为false,这样SharePoint平台就不会自动处理这个异常。下面是一段实例代码:

// for the assignment site, if the user doesn't have permission to view it
// we'll catch the exception
bool previousValue = SPSecurity.CatchAccessDeniedException;
SPSecurity.CatchAccessDeniedException = false;
try
{
    using (SPSite spSite = new SPSite(strWebUrl))
    {
      using (SPWeb spWeb = spSite.OpenWeb())
      {
            //do some operations. An access denied exception may be thrown from here.
      }
    }
}
catch (UnauthorizedAccessException)
{
    //do nothing. Catch the exception to not to restrict the user to access the content if user does not have access to SPWeb.
}
catch (FileNotFoundException)
{
    // do nothing . Catch the exception to not to restrict the user to access the content if SPWeb does not exist.
}
finally
{
    SPSecurity.CatchAccessDeniedException = previousValue;
}
    使用SPSecurity.CatchAccessDeniedException来防止跳到“拒绝访问”页面是官方推荐的方法,还有另外一个方法是设置Microsoft.SharePoint.SPSite.CatchAccessDeniedException属性,这个属性是SharePoint保留给自己内部使用的,不建议在我们的开发代码中使用。
  参考:
How to avoid Access denied page
SPSecurity.CatchAccessDeniedException Property (Microsoft.SharePoint)
SPSite.CatchAccessDeniedException Property (Microsoft.SharePoint)
  作者:黎波
博客:http://bobli.cnblogs.com/
日期:2008年10月23日
页: [1]
查看完整版本: [SharePoint]如何防止从代码跳到“拒绝访问”页面