首页 > 其他分享 >Sitecore 通过 processor 来自定义类似 github 的 not found 页面

Sitecore 通过 processor 来自定义类似 github 的 not found 页面

时间:2024-09-02 15:06:11浏览次数:4  
标签:github string Site Context Sitecore found httpContext null

有一个需求是类似 github 的 404 页面,当访问不存在的页面时,需要满足以下几点:

  1. 不是通过redirect或其他状态码让浏览器来跳转到到404页面;
  2. 链接还是原来链接,但是页面内容是 404;
  3. 由于是MVC模式,功能由 back-end 来实现;
  4. 状态码得是 404。

image

在基于 sitecore 的框架上,使用 sitecore 的 processor 来实现此功能:
文档地址:https://doc.sitecore.com/xp/en/developers/latest/sitecore-experience-manager/mvc-and-pipelines.html#mvc-specific-processors

using System.Net;
using System.Web;
using Sitecore.Diagnostics;
using Sitecore.Layouts;
using Sitecore.Pipelines.HttpRequest;
using Sitecore.Web;

namespace SitecoreConsole
{
    public class NotFoundProcessor : Sitecore.Pipelines.HttpRequest.HttpRequestProcessor
    {
        public string ItemNotFoundItemPath { get; set; }
        public string MapContentItemPath { get; set; }

        public override void Process(HttpRequestArgs args)
        {
            string siteStartPath = Sitecore.Context.Site.StartPath;
            PageContext page = Sitecore.Context.Page;
            string filePath = page?.FilePath;

            if (Sitecore.Context.Item != null || Sitecore.Context.Site == null || Sitecore.Context.Database == null)
            {
                return;
            }

            if (Sitecore.Context.Item == null)
            {
                string fullUrl = WebUtil.GetFullUrl(WebUtil.GetRawUrl());
                string cacheKey = $"cacheKey_{fullUrl}";
                
                string isActiveCache = string.Empty;
                if (Sitecore.Context.Site.CacheHtml && (isActiveCache = Sitecore.Context.Site.Caches.HtmlCache.GetHtml(cacheKey)) == "active")
                {
                    return;
                }

                // 这个是处理一个 AutoLinkMap,将一个链接映射到另一个链接的程序,此处可以是不到此功能
                // if (string.IsNullOrEmpty(isActiveCache))
                // {
                //     var mapContentItem = Sitecore.Context.Database.GetItem(string.Concat(siteStartPath, MapContentItemPath));
                //     if (mapContentItem != null)
                //     {
                //         if (!string.IsNullOrEmpty(mapContentItem.Fields["XML Mapping"]?.Value))
                //         {
                //             string mapContent = mapContentItem.Fields["XML Mapping"].Value;
                //             if (mapContent.IndexOf($"<oldlink>{fullUrl}</oldlink>", StringComparison.OrdinalIgnoreCase) != -1)
                //             {
                //                 if (Sitecore.Context.Site.CacheHtml)
                //                 {
                //                     Sitecore.Context.Site.Caches.HtmlCache.SetHtml(cacheKey, "active");
                //                 }
                //
                //                 return;
                //             }
                //         }
                //     }
                //
                //     if (Sitecore.Context.Site.CacheHtml)
                //     {
                //         Sitecore.Context.Site.Caches.HtmlCache.SetHtml(cacheKey, "disabled");
                //     }
                // }

                var notFoundItem = Sitecore.Context.Database.GetItem(string.Concat(siteStartPath, ItemNotFoundItemPath));
                if (notFoundItem != null)
                {
                    HttpContextBase httpContext = args.HttpContext;
                    if (httpContext != null)
                    {
                        httpContext.Items["PageNotFound"] = 1;
                    }

                    Sitecore.Context.Item = notFoundItem;
                    Log.Debug("[NotFoundProcessor] Set to item " + notFoundItem.Paths.FullPath, this);
                }
                else
                {
                    Log.Debug("[NotFoundProcessor] notFoundItem not found", this);
                }
            }
        }
    }
    
    public class SetHttpResponseCode : HttpRequestProcessor
    {
        public override void Process(HttpRequestArgs args)
        {
            HttpContextBase httpContext = args.HttpContext;
            if (httpContext != null)
            {
                if (Sitecore.MainUtil.GetBool(httpContext.Items["PageNotFound"], false))
                {
                    HttpContext.Current.Response.TrySkipIisCustomErrors = true;
                    HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.NotFound;
                }
            }
        }
    }
}

配置文件

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
    <sitecore role:require="ContentDelivery">
        <pipelines>
            <httpRequestBegin>
                <processor type="SitecoreConsole.NotFoundProcessor, SitecoreConsole"
                           patch:before="processor[@type='Sitecore.Pipelines.HttpRequest.LayoutResolver, Sitecore.Kernel']">
                    <ItemNotFoundItemPath>/404</ItemNotFoundItemPath>
                    <!--<LinkMapContentItemPath>/Map Content</LinkMapContentItemPath>-->
                </processor>
            </httpRequestBegin>
            <httpRequestEnd>
                <processor type="SitecoreConsole.SetHttpResponseCode, SitecoreConsole"
                           patch:after="processor[@type='Sitecore.Pipelines.HttpRequest.EndDiagnostics, Sitecore.Kernel']" />
            </httpRequestEnd>
        </pipelines>
    </sitecore>
</configuration>

标签:github,string,Site,Context,Sitecore,found,httpContext,null
From: https://www.cnblogs.com/fires/p/18392421

相关文章

  • 《HelloGitHub》第 101 期
    每月28号更新的开源月刊,这里有实战项目、入门教程、黑科技、开源书籍、大厂开源项目等,涵盖多种编程语言Python、Java、Go、C/C++、Swift...让你在短时间内感受到开源的魅力,对编程产生兴趣!兴趣是最好的老师,HelloGitHub让你对编程感兴趣!简介HelloGitHub......
  • 【愚公系列】《AIGC辅助软件开发》002-AI智能化编程助手:GitHub Copilot
    ......
  • GitHub每日最火火火项目(8.31)
    项目名称:Cinnamon/kotaemon项目介绍:kotaemon是一个基于开源RAG(检索增强生成)的工具,主要用于与文档进行聊天。它允许用户与自己的文档进行交互,提出问题并获取相关的回答。通过利用RAG技术,该工具能够从文档中检索信息,并以自然语言的方式与用户进行对话,帮助用户更好地理解和......
  • GitHub每日最火火火项目(8.29)
    项目名称:goauthentik/authentik项目介绍:authentik是一个提供认证功能的工具,它就像是你在数字世界中的身份验证胶水,能够确保你的系统和应用的安全性。它可能具备强大的功能,能够满足各种复杂的认证需求,为用户提供可靠的身份验证体验。项目地址:https://github.com/goauthe......
  • NGraphX v1.8.2发布,Bug修复及增加AiEditor接入示例并托管示例源码到Github
    本次更新包括了对启动脚本、认证流程、请求Url处理的优化,以及工作流API的改进。此外,我们还新增了AiEditor接入示例,让用户体验更直观、互动性更强。示例更新内容:启动脚本主机参数默认值修改:修改启动脚本中主机参数的默认值为127.0.0.1,以增强本地访问的安全性。如需开启......
  • 基于live555开发的多线程RTSPServer轻量级流媒体服务器EasyRTSPServer开源代码及其调
    EasyRTSPServer参考live555testProg中的testOnDemandRTSPServer示例程序,将一个live555testOnDemandRTSPServer封装在一个类中,例如,我们称为ClassEasyRTSPServer,在EasyRTSPServer_Create接口调用时,我们新建一个EasyRTSPServer对象,再通过调用EasyRTSPServer_Startup接口,将EasyRTSP......
  • GitHub 上这款新浪微博爬虫项目,‌让你轻松掌握微博数据!‌
    该文章为weibo-crawler的官方文档,为了方便国内的同学阅读而转载。原文地址:https://github.com/dataabc/weibo-crawler源码我也下载了一份,读者可以在我的公众号上回复“分享资料”来获取,路径如下:​‍‍以下是正文:功能连续爬取一个或多个新浪微博用户(如迪丽热巴、郭碧婷)的......
  • ModuleNotFoundError: No module named ‘utils.query‘ flask项目遇到这种报错怎么解
    ModuleNotFoundError:Nomodulenamed'utils.query'这个错误表明你的Python代码正在尝试导入一个名为utils.query的模块,但未能成功找到它。以下是解决该问题的几个步骤:1.检查模块路径如果utils.query是你自己的模块或在项目中的某个目录下,确保文件路径正确。util......
  • 给Hexo博客安排上Github Action自动化部署
    我不是换hexo了吗,一直是使用SpckEditor写文章,每次写好文章都要push一次,非常麻烦,最近在群友那了解到有GithubAction自动化部署,可以写好文章自动部署到githubpages,而且github的编辑器也是非常好用的,写好提交就能自动发送,–怎么有点像SSR了–,于是我就开始了这一个半小时的折腾…......
  • 修改 Linux 默认 Shell 用 chsh -s /bin/zsh 命令不生效,提示 chsh: Shell not changed
    我想现在应该有很多人都已经使用zsh作为默认的Shell了,尤其是搭配oh-my-zsh之后,真是好用得飞起。一般,我们在切换系统默认的Shell的时候,都会使用 chsh-s/bin/zsh 命令来进行修改。今天我遇到一个问题,在某台老服务器上,使用这个命令无法修改,具体原因未知。始终提示——chsh:She......