Monday, June 14, 2010

Handling AccessDenied Exception to implement our logic


The SPUtility.HandleAccessDenied method provides the functionality to redirect users to the standard "Access Denied Page" pragmatically, thus asking them to re-logon. One of the scenarios of such usage is the public sites, where access to the standard SharePoint specific pages still exists and you want to block those pages
However, you can handle access denied exception via SPSecurity.CatchAccessDeniedException = true
Access deined exception is handled by sharepoint platform and user will be redirected to _layouts/AccessDenied.aspx page if user doesnt have permission to perform that task. This might casue usability problem in some cases. You can handle access denied exception in your code by setting CatchAccessDeniedException value to true.
Following code snippet shows how to handle access denied exception:

bool catchException = SPSecurity.CatchAccessDeniedException;
SPSecurity.CatchAccessDeniedException = false;
try
{
//updating list item
SPList list = SPcontext.Current.Web.List["TestList"];
SPListItem item = list.Items[0];
item["title"] = "Some value";
//If user doesnt have permission, exception will be thrown
//If value of CatchAccessDeniedException is true, then user will be
//redirected to AccessDenied.aspx page
item.Update();
}
cach(Exception ex)
{
//Your custom error message can be shown here
}
finally
{
//reset the flag to original value
SPSecurity.CatchAccessDeniedException = catchException;
}

No comments:

Post a Comment