Pages

Friday, May 9, 2014

Configure Custom Access Denied Page - BUG in SharePoint 2013

There are many reasons that lead to the need to have your own Custom Access Denied Page, such as changing the text of the message or adding a more dynamic page / form to collect information from the user or perform some other function. Once you build your page and get it deployed to Layouts Folder and use below Powershell Commands


We can use the following PowerShell command for it

$web = Get-SPWebApplication http://WebApplicationURL/
Set-SPCustomLayoutsPage -Identity AccessDenied –RelativePath "/_layouts/15/Folder/CustomAccessDeniedPage.html" -WebApplication $web

Or

$web = Get-SPWebApplication http://WebApplicationURL/
$web.UpdateMappedPage([Microsoft.SharePoint.Administration.SPWebApplication+SPCustomPage]::AccessDenied, "/_layouts/15/Folder/CustomAccessDeniedPage.html ")
$web.Update()

Check the set property with below PowerShell command

$web = Get-SPWebApplication http://WebApplicationURL/
Get-SPCustomLayoutsPage -Identity AccessDenied -WebApplication $web | Format-List

You will observe the updated Value but when you try browsing you will get the default AccessDenied Page but not the custom access denied page. This is a known bug in SharePoint 2013 product. Till now with the current release of CU1 in Feb 2014, this issue is not been fixed.


Inorder to accomplish this, you can go with HttpHandler or HttpModule. Here we preferred to go with HttpModule and below is the code snippet for it.


public class CustomAccessDenied : IHttpModule
{
public void Init(HttpApplication app)
{
app.PreRequestHandlerExecute += new EventHandler(app_PreRequestHandlerExecute);
}
void app_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
string str = Path.GetFileName(new Uri(context.Request.Url.AbsoluteUri).LocalPath);

if (str.ToLower().Equals("accessdenied.aspx"))
{
context.Response.Redirect("/_layouts/15/customaccessdenied.aspx",true);
}
}

public void Dispose()
{
}
}


Note:- The custom access denied page [aspx] should has to Inherit from "Microsoft.SharePoint.ApplicationPages.AccessDeniedPage" class.
e.g. <%@PageLanguage="C#"Inherits="Microsoft.SharePoint.ApplicationPages.AccessDeniedPage"MasterPageFile="~/_layouts/simple.master"%>

Now write your c# code inline in PlaceHolderMain in the .aspx page. (This is the drawback).

2 comments:

  1. can you please let me know how to create an httpmodule in visual studio and deploy itca

    ReplyDelete
    Replies
    1. Hi Harsh Damania,

      Thank you for your comment.

      Here's is the step wise procedure of how to create HTTP Module, explained with example for this one. I think you can directly copy and paste the code.

      http://a2zdinesh.blogspot.in/2014/06/create-httpmodule-step-wise-explained.html

      Please let me now if any more info required.

      Thanks, Dinesh

      Delete