我正在开发Umbraco 7 MVC应用程序,我的要求是在Umbraco中添加 Item 。 项目名称应该是唯一的。对于使用下面的代码,但我收到错误“哎呀:这个文件已发布但不在缓存中(内部错误)”
protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication,
ApplicationContext applicationContext)
{
ContentService.Publishing += ContentService_Publishing;
}
private void ContentService_Publishing(IPublishingStrategy sender, PublishEventArgs<IContent> e)
{
try
{
if(newsItemExists)
{
e.Cancel = true;
}
}
catch (Exception ex)
{
e.Cancel = true;
Logger.Error(ex.ToString());
}
}
然后我尝试添加代码以取消发布但它不起作用,即节点正在发布。以下是我的代码
private void ContentService_Publishing(IPublishingStrategy sender, PublishEventArgs<IContent> e)
{
try
{
int itemId=1234; //CurrentPublishedNodeId
if(newsItemExists)
{
IContent content = ContentService.GetById(itemId);
ContentService.UnPublish(content);
library.UpdateDocumentCache(item.Id);
}
}
catch (Exception ex)
{
e.Cancel = true;
Logger.Error(ex.ToString());
}
}
但是使用上面的代码,如果你给CurrentPublishedNodeId = 2345 // someOthernodeId它的未发布正确。
你能帮我解决这个问题。
答案 0 :(得分:2)
您不必这样做,如果该项目已存在,Umbraco会自动将(1)
附加到该名称(因此它是唯一的)。
如果您不想要这种行为,可以通过以下方式检查:
protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
ContentService.Publishing += ContentService_Publishing;
}
private void ContentService_Publishing(Umbraco.Core.Publishing.IPublishingStrategy sender, PublishEventArgs<IContent> e)
{
var contentService = UmbracoContext.Current.Application.Services.ContentService;
// It's posible to batch publish items, so go through all items
// even though there might only be one in the list of PublishedEntities
foreach (var item in e.PublishedEntities)
{
var currentPage = contentService.GetById(item.Id);
// Go to the current page's parent and loop through all of it's children
// That way you can determine if any page that is on the same level as the
// page you're trying to publish has the same name
foreach (var contentItem in currentPage.Parent().Children())
{
if (string.Equals(contentItem.Name.Trim(), currentPage.Name.Trim(), StringComparison.InvariantCultureIgnoreCase))
e.Cancel = true;
}
}
}
我认为您的问题可能是您没有循环遍历所有PublishedEntities
,而是使用其他方式来确定当前页面ID。
注意:请不要使用library.UpdateDocumentCache
这个,完全没有必要,ContentService.UnPublish将负责缓存状态。