如何为控制器操作附加Sitecore上下文以映射robots.txt?

时间:2015-02-09 17:13:29

标签: sitecore robots.txt sitecore-mvc sitecore8

在Sitecore中,我正在尝试为客户端设置修改内容树中robots.txt文件的方法。我正在尝试设置一个MVC控制器操作,该操作被映射到路由“robots.txt”并将返回文件内容。我的控制器看起来像这样:

public class SeoController : BaseController
{
  private readonly IContentService _contentService;
  private readonly IPageContext _pageContext;
  private readonly IRenderingContext _renderingContext;

  public SeoController(IContentService contentService, IPageContext pageContext, IRenderingContext renderingContext, ISitecoreContext glassContext)
     : base(glassContext)
  {
     _contentService = contentService;
     _pageContext = pageContext;
     _renderingContext = renderingContext;
  }

  public FileContentResult Robots()
  {
     string content = string.Empty;
     var contentResponse = _contentService.GetRobotsTxtContent();

     if (contentResponse.Success && contentResponse.ContentItem != null)
     {
        content = contentResponse.ContentItem.RobotsText;
     }

     return File(Encoding.UTF8.GetBytes(content), "text/plain");
  }
}

路线配置:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        RouteTable.Routes.MapRoute("Robots.txt", "robots.txt", new { controller = "Seo", action = "Robots" });
    }
}

如果我使用没有“.txt”扩展名的路线,这一切都很有用。但是,添加扩展后,由于上下文数据库为空,我在域层中获得了一个空引用异常。这是错误发生的地方:

public Item GetItem(string contentGuid)
{
    return Sitecore.Context.Database.GetItem(contentGuid);
}

我假设sitecore中有一个忽略.txt扩展名的设置。我已经尝试将其添加为配置的Sitecore.Pipelines.PreprocessRequest.FilterUrlExtensions设置中的允许扩展名。还有什么我可以错过的吗?

2 个答案:

答案 0 :(得分:3)

好的,我发现了这个问题。假设需要将txt添加到Sitecore.Pipelines.PreprocessRequest.FilterUrlExtensions设置的允许扩展名中,我是正确的。但是,robots.txt列在配置文件中的IgnoreUrlPrefixes设置下。这导致sitecore忽略该请求。我从列表中删除了它,现在它运行得很好。

答案 1 :(得分:1)

这是一个纯粹的猜测,但您可能还需要将其添加到Sitecore.Pipelines.HttpRequest.FilterUrlExtensionshttpRequestBegin的允许扩展名中。