Kentico - Call 404 Page From Code

There will be times when you want to direct a user to a 404 page based on certain conditions from within your code. For example, when dealing with pages that use wildcard URL's, you might want to redirect the user to a 404 page if the value of that wildcard parameter returns no data.

In my blog I have two wildcard parameters to allow the user to filter my posts by either category or tag. At code-level if no blog posts are returned based on the category or tag value, I have two choices:

  1. Display a "no results" message
  2. Redirect to a 404 page

As you can tell by the title of this post, I wanted to go for the latter.

From a Kentico perspective wildcard parameters in a URL aren't what I call "proper" pages and the CMS routing engine won't send you a 404 page as you'd think. So we need to carry the redirect at code-level ourselves based on the conditions we provide. As far as I'm aware, Kentico doesn't have a method in code to do this and settled for a workaround suggested by S├ębastien Gumy in the following DevNet post.

I made some minor changes to the code and placed it in a helper method for use throughout my project with ease:

using CMS.Helpers;
using CMS.PortalEngine;
using CMS.URLRewritingEngine;

namespace Site.Common.Kentico
{
    public class PortalContextHelper
    {
        /// <summary>
        /// Redirect page to 404.
        /// </summary>
        public static void SendToPageNotFound()
        {
            PortalContext.Clear();
            CMSHttpContext.Current.Response.StatusCode = 404;
            URLRewriter.RewriteUrl(RequestStatusEnum.PageNotFound, string.Empty, ExcludedSystemEnum.Unknown);
        }
    }
}

The SendToPageNotFound() method can then be used in the following way:

#region Get Querystring Parameters

string tag = QueryHelper.GetString("Tag", string.Empty);
string category = QueryHelper.GetString("Category", string.Empty);
int pageNo = QueryHelper.GetInteger("PageNo", 1);

#endregion

int tagId = TagLogic.GetTagIdFromQuerystring(tag);

// A custom method to get back blog posts based on parameters.
BlogListing postData = BlogLogic.GetBlogPosts(CurrentDocument.NodeAliasPath, category, tagId, (pageNo - 1));

if (postData.BlogPosts != null)
{
    BlogListing.DataSource = postData.BlogPosts;
    BlogListing.DataBind();
}
else
{
    // Send to 404 page.
    PortalContextHelper.SendToPageNotFound();
}

Please note: This has only been tested in Kentico 10.

blog comments powered by Disqus