Redirection to different item without changing URL in Sitecore if Requested URL matches Linkfield URL in item

Posted 09/09/2016 by Arpit Katiyar

Recently, I got a requirement from client for a scenario that every item shall hold 10 redirect fields and if we save any URL into those fields and the request URL matches to these URL, the page should redirect to item holding the URL but the requested URL should remain the same.

After some analysis and research I found a way to achieve this by passing item ID of redirecting item to tracker of alias and rest will be handled by alias in sitecore.

Here is the detailed description for a solution to such requisite scenario.

1. First we created the index class for all the 10 redirect fields:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.SearchTypes;

namespace [namespace]
{
    public class SearchField : SearchResultItem
    {
        [IndexField("RedirectURL1")]
        public string RedirectURL1 { get; set; }

        [IndexField("RedirectURL2")]
        public string RedirectURL2 { get; set; }

        [IndexField("RedirectURL3")]
        public string RedirectURL3 { get; set; }

        [IndexField("RedirectURL4")]
        public string RedirectURL4 { get; set; }

        [IndexField("RedirectURL5")]
        public string RedirectURL5 { get; set; }

        [IndexField("RedirectURL6")]
        public string RedirectURL6 { get; set; }

        [IndexField("RedirectURL7")]
        public string RedirectURL7 { get; set; }

        [IndexField("RedirectURL8")]
        public string RedirectURL8 { get; set; }

        [IndexField("RedirectURL9")]
        public string RedirectURL9 { get; set; }

        [IndexField("RedirectURL10")]
        public string RedirectURL10 { get; set; }
    }
}

2. Now we will compare the request URL with the urls in the redirect field using lucene search and then we will pass the output to Tracer. Info of alias which will handle the redirect and maintain the same URL.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.Linq.Utilities;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using [Namespace].CustomSearchField;
using Sitecore.Links;
using Sitecore.Pipelines.HttpRequest;
using Sitecore;
using Sitecore.Configuration;
using Sitecore.Diagnostics;
using System.Net;
using AliasResolver;

namespace [Namespace]
{
    public class CustomUrlRedirect : Sitecore.Pipelines.HttpRequest.HttpRequestProcessor
    {
        public string filePath { get; set; }
        public override void Process(Sitecore.Pipelines.HttpRequest.HttpRequestArgs args)
        {
            filePath = HttpContext.Current.Request.Url.AbsolutePath;
            var redirect = GetRequestedResult(filePath);

            if (redirect!=null)
            {
                Tracer.Info(string.Concat("Using alias for \"", args.LocalPath, "\" which points to \"", redirect.ID, "\""));
            }
        }


        public Item GetRequestedResult(string requestedURL)
        {
            Item ContextItem = Sitecore.Context.Database.GetItem(Sitecore.Context.Site.ContentStartPath);
            Item Result = null;
            using (var context = ContentSearchManager.GetIndex((SitecoreIndexableItem)ContextItem).CreateSearchContext())
            {
                IEnumerable item = null;
                var Results = context.GetQueryable();
                for (int i = 1; i <= 10; i++)
                { 
                    var fieldName = "RedirectURL" + i;
                    item = Results.Where(j => !string.IsNullOrEmpty(j[fieldName]) && RemoveDomainNameFromURL(j[fieldName]) == (requestedURL)).Select(m => (Item)m.GetItem()).ToList();
                    if (item != null && item.Any())
                    {
                        break;
                    }
                    if (item == null && fieldName == "RedirectURL10")
                    {
                        return Result;
                    }
                }

                Result = item.FirstOrDefault();
            }
            return Result;
        }
        public static string RemoveDomainNameFromURL(string Url)
        {
            if (!string.IsNullOrEmpty(Url))
            {
                var newURL = Url;
                if (Url.Contains(@"://"))
                {
                    Url = Url.Split(new string[] { "://" }, 2, StringSplitOptions.None)[1];
                    Url = Url.Split('/')[0];
                    newURL = newURL.Replace(Url, "");
                    return newURL.Replace("http://", "");
                }
                return Url;
            }
            return string.Empty;
        }

    }

}

3. Now let’s create a configuration file to run this on every request made.

<?xml version="1.0" encoding="utf-8"?>

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/">
    <pipelines>
      <httpRequestBegin>
        <processor patch:after="*[@type='Sitecore.Pipelines.HttpRequest.AliasResolver, Sitecore.Kernel']" type="[Namespace].CustomUrlRedirect, [Namespace]"/>
      </httpRequestBegin>
    </pipelines>
  </sitecore>
</configuration>

This mechanism worked for me, and I trust if you're reading this, it might make your life easier too!

Share:

Archive

Syndication