詳細可以參考這個網站
節錄摘要,
if (oWeb.DoesUserHavePermissions(SPBasePermissions.ViewPages))
{
SPList oList = oWeb.Lists[ListName];
if (oList.DoesUserHavePermissions(SPBasePermissions.ViewListItems))
{
// some smart code
}
}
因為要先Get Web或是List的物件才能進行判斷,所以如果該使用者對該物件沒有權限,這樣寫可能會當掉,所以建議寫法如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| SPUser User = SPContext.Current.Web.CurrentUser;
SPSecurity.RunWithElevatedPrivileges(delegate { using (SPSite Site = new SPSite(SPContext.Current.Site.ID)) { using (SPWeb Web = Site.OpenWeb(WebName)) { if(Web.DoesUserHavePermissions(User.LoginName,SPBasePermissions.ViewPages)) { SPList List = Web.GetList(URL); if(List.DoesUserHavePermissions(User, SPBasePermissions.ViewPages)) { HavePermission = true; } } } } });
|
或是
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
private bool CheckPermission(SPWeb _web) { Boolean catchException = SPSecurity.CatchAccessDeniedException; SPSecurity.CatchAccessDeniedException = false; try { if (_web.DoesUserHavePermissions(currentUser.LoginName, SPBasePermissions.ViewPages)) { return true; } else { return false; } } catch { return false; } finally { SPSecurity.CatchAccessDeniedException = catchException; } }
|