While executing custom code in SharePoint, one might run into instances where a user suddenly gets “Access Denied” error message i.e. the user gets redirected to the “_layouts/AccessDenied.aspx” page. These kind of situations usually occur when a user tries to perform a particular task which he/she does not have permission to do. These user permission issues can be handled to some extent programmatically in the code.
The following code snippet shows an example of how one can use the “CatchAccessDeniedException” property of the “SPSecurity” class to get rid of the “Access Denied” issue.
using (SPSite spSite = newSPSite("http ://mySPSiteUrl/"))
spSite.AllowUnsafeUpdates = true;
using (SPWeb spWeb = oSite.OpenWeb())
spWeb.AllowUnsafeUpdates = true;
spWeb.Site.CatchAccessDeniedException = false;
// Perform the task here
spWeb.Site.CatchAccessDeniedException = true;
spWeb.AllowUnsafeUpdates = false;
spSite.AllowUnsafeUpdates = false;