MOSS / Sharepoint 2007 Custom Error Page and Access denied Page



MOSS / Sharepoint 2007 Custom Error Page and Access denied Page


In case if you are interested in creating your own custom error page and custom access denied page instead of the out of the box MOSS / Sharepoint error page (generally the requirements in Publishing internet site). You can use the following HTTPModule (this is just a sample, you can change it to suit your requirements):


 


Note to have following Web.config Entries:


Following entries in the <appsettings> section in the web.config file:



  1. Following entry is for a custom error page to be displayed for anonymous users, the key should be in the format: “CustomAnonCustErrPG-SiteCollectionURL” as shown below:

<add key=”CustomAnonCustErrPG-http://xyz.com” value=”/Pages/default.aspx” />



  1. Following entry is for a custom error page to be displayed for authenticated users, the key should be in the format: “CustomAuthCustErrPG-SiteCollectionURL” as shown below:

<add key=”CustomAuthCustErrPG-http:// xyz.com ” value=”/Pages/default.aspx” />



  1. Following entry is for a custom error page to be displayed for access denied errors, the key should be in the format: “CustomCustAcsDndPG -SiteCollectionURL” as shown below:

<add key=”CustomCustAcsDndPG-http://xyz.com” value=”/_layouts/XYZ/CustomErrPg.aspx ” />


 



Create an entry on all the WFEs web-application specific web.config in the HTTPModules section, as follows just below the <HTTPModule> tag This should be the first entry in the HTTPModules section:


<add name=”XYZExceptionHandler” type=”XYZ.Sharepoint.HTTPModule.CustomErrorPages.CustomErrors, XYZ.Sharepoint.HTTPModule.CustomErrorPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=PUBLICKEYGUID” />


 


NOTE: Add your own Public key for PublicKeyToken per your snk used, replace the PUBLICKEYGUID with your own snk value


 


///////////////////////////////////////////////////////////////////////////////////////////////


// This is a HTTPModule used for redirecting the user to Home or Home Anon site depending on whether


// s/he is authenticated or anonymous.


//


// The module checks if the url is accessdenied.aspx and redirects the user to proper url.


////////////////////////////////////////////////////////////////////////////////////////////////


 


using System;


using System.Web;


using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;


using System.Configuration;


using Microsoft.SharePoint;


 


namespace XYZ.Sharepoint.HTTPModule.CustomErrorPages


{


    public class CustomErrors : IHttpModule


    {


 


        #region — Private fields —


 


        private static AppSettingsReader m_Reader = new AppSettingsReader();


        private static string m_SiteCollAnonCustomErrPG = “CustomAnonCustErrPG”;


        private static string m_SiteCollAuthCustomErrPG = “CustomAuthCustErrPG”;


        private static string m_SiteCollCustAcsDndPG = “CustomCustAcsDndPG”;


       


        #endregion


 


 


        public void Init(HttpApplication context)


        {


            //Attaching event handlers for access denied and error respectively


            //context.BeginRequest += new EventHandler(context_AcessDenied);


            context.EndRequest += new EventHandler(context_AcessDenied);


            context.Error += new EventHandler(context_Error);


 


        }


 


        void context_AcessDenied(object sender, EventArgs e)


        {


            try


            {


                HttpApplication httpApp = sender as HttpApplication;


                HttpContext context = httpApp.Context;


 


                string httpUrl = context.Request.Url.ToString();


                string strCustomAcssDndURL = string.Empty;


                string strSiteURL = string.Empty;


 


                if (httpUrl.ToLower().Contains(“/_layouts/accessdenied.aspx”))


                {


                    SPSecurity.RunWithElevatedPrivileges(delegate()


                    {


                        using (SPSite site = new SPSite(httpUrl))


                        {


                            strSiteURL = site.Url;


                        }


                    });


                    HttpContext.Current.Server.ClearError();


                    HttpContext.Current.Response.Clear();


                    strCustomAcssDndURL = getAppSettingsValue(m_SiteCollCustAcsDndPG + “-” + strSiteURL);


                    HttpContext.Current.Response.Redirect(strCustomAcssDndURL, false);


                }


            }


            catch (Exception ex)


            {


                //Do your exception handling


            }


          }


 


 


        void context_Error(object sender, EventArgs e)


        {


            try


            {


                string strURL = string.Empty;


                string strSiteURL = SPContext.Current.Site.Url;


                Exception[] unhandledExceptions = HttpContext.Current.AllErrors;


                //logging all the exceptions thru the Exception policy file


                foreach (Exception ex in unhandledExceptions)


                {


                //Do your exception handling


                }


 


                HttpContext.Current.Server.ClearError();


                HttpContext.Current.Response.Clear();


 


                if (HttpContext.Current.User.Identity.IsAuthenticated)


                {


                    strURL = getAppSettingsValue(m_SiteCollAuthCustomErrPG + “-” + strSiteURL);


                    HttpContext.Current.Response.Redirect(strURL, false);


                }


                else


                {


                    strURL = getAppSettingsValue(m_SiteCollAnonCustomErrPG + “-” + strSiteURL);


                    HttpContext.Current.Response.Redirect(strURL, false);


                }


            }


            catch (Exception ex)


            {


                //Do your exception handling


            }


        }


        


        public void Dispose()


        {


        }


 


        //Method used to read Appsettings value from web.config for the webapplication


        private static string getAppSettingsValue(string sKey)


        {


            string sValue = null;


 


            try


            {


                sValue = m_Reader.GetValue(sKey, typeof(string)) as string;


            }


            catch (Exception ex)


            {


                                //Do your exception handling


            }


 


            return sValue;


        }


    }


}

Comments (6)

  1. anjolait says:

    I have used this to update the error pages and it is working quite well.  I have one problem though, I have to not allow the userlist to be viewed by my customers and have set permissions accordingly but instead of getting an access denied page or my custom error page, I get "Unable to find user".  Any ideas why this is happening? If so, any suggestions on how to prevent it?

  2. shanemalhotra says:

    Well…Code in accessdenied needs to be tweaked to simulate the OOTB behavior.

    When first request goes to accessdenied from Sign is as different user, then there is a parameter called "loginasanotheruser=true", which must be passed to your custom page, only then you get windows authentication challenge otherwise not.

    Subsequent request doesn’t contain that parameter so you should also remove it from the custom page request.

    Hope it helps!

  3. Cheri Ramos says:

    I would like to customize my error messages, because some of them are pretty standard, but i want to make sure I am updating the appropriate web.config file.  Should I be going to the one in GlobalShared or in the 12 hive?  or someother file all together?  Thanks

  4. Venkat says:

    Above mechanism works when there callstack is set to true in web.config. Any other alternative without modifying callstack value.

  5. Daniel says:

    I want to set custom access denied at the sub site level and not say for the whole site collection. Is this possible?

    Regards

    Daniel

  6. Fran says:

    This looks promising. Do you save the module as a .dll file? Where do you place the module? In the bin folder of the web site?