In every Sitecore application, if end user type some
page name that is not exist then we need to redirect user to some custom page
which inform user that requested page is not available.
Here are the steps for it.
·
Create template, layout and content item
for Page not found.
·
Write below code in your project
namespace MyProject.CodeFiles
{
/// <summary>
/// 404 class
/// </summary>
public class Page404Resolver : Sitecore.Pipelines.HttpRequest.HttpRequestProcessor
{
public override void Process(Sitecore.Pipelines.HttpRequest.HttpRequestArgs args)
{
if (Sitecore.Context.Item != null || Sitecore.Context.Site == null || Sitecore.Context.Database == null)
{
return;
}
// If
current item not available in Sitecore, then
if (Sitecore.Context.Item == null)
{
Sitecore.Diagnostics.Log.Info("Page404Resolver=" +
System.Web.HttpContext.Current.Request.Url,
this);
//
Find an error-page item and set it to context Item
Item item404 = args.GetItem(new ID("{XXXXX1D2-8CDB-4461-93CE-501905DDSSSS}"));
if (item404 != null)
{
Sitecore.Context.Item = item404;
Sitecore.Context.Items["is404"] = "true";
Sitecore.Diagnostics.Log.Info("CUSTOM ERROR HANDLER: 404 : Item is not null - Setting Context item to
404 page", this);
}
}
}
}
}
·
Open web.config file and add this class
just below ItemResolver line
of pipeline section
<processor type="Sitecore.Pipelines.HttpRequest.ItemResolver,
Sitecore.Kernel"/>
<processor type="MyProject.Web.Present.CodeFiles.Page404Resolver,
MyProject.Web.UI"/>
·
Implement below code in page load section
of File Not Found page. Keep response status as 404 and also set status of
response.
public partial class NotFound : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (Sitecore.Context.Items["is404"].Equals("true"))
{
try
{
Response.StatusCode =
404;
Response.TrySkipIisCustomErrors = true;
Response.StatusDescription
= "File not found";
//Response.End();
}
catch (Exception ex)
{
// Log error
}
}
}
}
Please leave your comments or share this code if it’s
useful for you.
No comments:
Post a Comment