Thursday, October 21, 2010

How to avoid Access denied page

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;
}

Reference: sridharu blog.

Thanks!
Avinash

No comments: