【发布时间】:2016-02-08 11:06:14
【问题描述】:
我构建了一个 Umbraco 7 站点并创建了一个站点地图文档类型,该文档类型在其 Razor 视图中呈现 XML 站点地图。
这工作正常,从 URL /sitemap/ 运行。
我现在正在尝试使用自定义路由来使该站点地图在 /sitemap.xml 中可用。根据各种在线建议,我使用以下方法创建了IApplicationEventHandler 的实现:
public void OnApplicationInitialized(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
//custom route
RouteTable.Routes.MapUmbracoRoute(
"sitemap",
"sitemap.xml",
new
{
controller = "XMLSitemap"
},
new XmlSitemapRouteHandler());
}
XmlSitemapRouteHandler 实现 UmbracoVirtualNodeRouteHandler 并覆盖以下方法:
protected override IPublishedContent FindContent(RequestContext requestContext, UmbracoContext umbracoContext)
{
var umbracoHelper = new UmbracoHelper(umbracoContext);
return umbracoHelper.TypedContent(_sitemapNodeId);
}
现在我有一个非常简单的关联控制器:
public class XMLSitemapController : RenderMvcController
{
public override ActionResult Index(RenderModel model)
{
return this.CurrentTemplate(model);
}
}
当我在浏览器中加载 /sitemap.xml 时,出现以下异常:
值不能为空。 参数名称:umbracoContext
这在var umbracoHelper = new UmbracoHelper(umbracoContext); 行。当我使用 UmbracoContext.Current 代替 umbracoContext 时,我得到了同样的结果。
似乎没有创建 UmbracoContext。我的应用程序使用依赖注入(StructureMap)并且确实为 UmbracoContext 指定了一个绑定:
For<Umbraco.Web.UmbracoContext>().Use(() => Umbraco.Web.UmbracoContext.Current);
我想知道这是否与 .xml 扩展名有关,所以我尝试将自定义路由 URL 更改为“sitemapxml”。现在,当我加载此 URL 时,出现以下异常:
RouteData 必须包含一个名为 'action' 且具有非空字符串值的项目。
我确实找到了一些建议 here,这表明在这种情况下可以使用 UmbracoContext.EnsureContext,因此我尝试将路由处理程序方法更新为以下内容:
protected override IPublishedContent FindContent(RequestContext requestContext, UmbracoContext umbracoContext)
{
var httpBase = new System.Web.HttpContextWrapper(System.Web.HttpContext.Current);
UmbracoContext.EnsureContext(
httpBase,
Umbraco.Core.ApplicationContext.Current,
new Umbraco.Web.Security.WebSecurity(httpBase, Umbraco.Core.ApplicationContext.Current),
true);
var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
return umbracoHelper.TypedContent(1090);
}
虽然代码报告此 EnsureContext 方法已过时,但我至少现在看到 UmbracoContext.Current 是一个有效的参考。但是,这次我仍然遇到异常:
对象引用未设置为对象的实例。
这是从 Umbraco.Web.Mvc.UmbracoVirtualNodeRouteHandler.GetHttpHandler(RequestContext requestContext) 的 Umbraco 程序集抛出的。
所以我被困住了。我原以为提供这样的自定义路线会相对容易。也许我完全采取了错误的方法。非常感谢您的建议。
【问题讨论】:
-
为什么不使用
http://www.yoursite.be/?alttemplate=XMLSitemap?它直接呈现您的站点地图 xml 而无需编写代码。 -
谢谢,这对了解很有帮助,但恐怕这并不能让我更接近于回答我关于使 Umbraco 呈现的 XML 可从 .xml 扩展名中获得的问题。
标签: c# asp.net-mvc umbraco7