我最近遇到了一个类似的情况,必须在 Web 服务中跟踪分析事件。正如您所指出的,问题在于 AnalyticsTracker.Current 在 Web 服务的上下文中为空。
原因是AnalytisTracker.Current 是在trackAnalytics 管道期间填充的,而renderLayout 管道期间又会调用该管道,该管道仅在上下文项不为空且上下文项具有演示文稿时调用设置已定义。
话虽如此,有一个解决方法:)
您可以像这样手动启动AnalyticsTracker:
if (!AnalyticsTracker.IsActive)
{
AnalyticsTracker.StartTracking();
}
然后您可以像这样检索AnalyticsTracker 实例:
AnalyticsTracker tracker = AnalyticsTracker.Current;
if (tracker == null)
return;
最后,您可以创建和触发您的事件、个人资料等...下面的示例触发PageEvent。注意:为了填充Timestamp 属性,需要特别考虑PageEvent(以及最有可能的其他事件)。请参阅下面代码中的 cmets。
if (!AnalyticsTracker.IsActive)
{
AnalyticsTracker.StartTracking();
}
AnalyticsTracker tracker = AnalyticsTracker.Current;
if (tracker == null)
return;
string data = HttpContext.Current.Request.UrlReferrer != null
? HttpContext.Current.Request.UrlReferrer.PathAndQuery
: string.Empty;
//Need to set a context item in order for the AnalyticsPageEvent.Timestamp property to
//be set. As a hack, just set the context item to a known item before declaring the event,
//then set the context item to null afterwards.
Sitecore.Context.Item = Sitecore.Context.Database.GetItem("/sitecore");
AnalyticsPageEvent pageEvent = new AnalyticsPageEvent();
pageEvent.Name = "Download Registration Form Submitted";
pageEvent.Key = HttpContext.Current.Request.RawUrl;
pageEvent.Text = HttpContext.Current.Request.RawUrl;
pageEvent.Data = data;
//Set the AnalyticsPageEvent.Item property to null and the context item to null.
//This way the PageEvent isn't tied to the item you specified as the context item.
pageEvent.Item = null;
Sitecore.Context.Item = null;
tracker.CurrentPage.TriggerEvent(pageEvent);
tracker.Submit();
希望这会有所帮助!