问题
I have an episerver project that has lots of blocks over time some of these blocks are no longer needed, is there a way to see if a created block is being used on any pages in my episerver website?
回答1:
I rarely do this but last time I did I used this code to get all published instances of a custom CodeBlock
// initiate the repos (use dependency injection instead of the ServiceLocator)
var contentTypeRepository = ServiceLocator.Current.GetInstance<EPiServer.DataAbstraction.IContentTypeRepository>();
var contentModelUsage = ServiceLocator.Current.GetInstance<IContentModelUsage>();
var repository = ServiceLocator.Current.GetInstance<IContentRepository>();
var linkRepository = ServiceLocator.Current.GetInstance<IContentSoftLinkRepository>();
// loading a block type
var blockType = contentTypeRepository.Load(typeof(CodeBlock));
// get usages, also includes versions
IList<ContentUsage> usages = contentModelUsage.ListContentOfContentType(blockType);
List<IContent> blocks = usages.Select(contentUsage =>
contentUsage.ContentLink.ToReferenceWithoutVersion())
.Distinct()
.Select(contentReference =>
repository.Get<IContent>(contentReference)).ToList();
var unusedBlocks = new List<IContent>();
foreach (IContent block in blocks)
{
var referencingContentLinks = linkRepository.Load(block.ContentLink, true)
.Where(link =>
link.SoftLinkType == ReferenceType.PageLinkReference &&
!ContentReference.IsNullOrEmpty(link.OwnerContentLink))
.Select(link => link.OwnerContentLink);
// if no links
if (!referencingContentLinks.Any())
{
unusedBlocks.Add(block);
}
}
You'll find the unused block instances in unusedBlocks
Now, as usual, don't use the ServiceLocator unless you like to hide dependencies.
来源:https://stackoverflow.com/questions/49454291/episerver-how-can-i-find-out-if-a-block-is-being-used-on-any-published-page