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

本文介绍在SharePoint平台上如何处理因权限不足导致的拒绝访问异常,通过禁用自动跳转功能,开发者可以在自己的代码中捕获并处理这类异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在代码中执行没有权限的操作时,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日

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值