Resolve the currently loaded content context
1 min
To resolve the current loaded content context, get an instance of the CurrentContentContext object. Run any custom logic in any of the Content events:
[InitializableModule]
[ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
public class CustomModule : IInitializableModule
{
private IContentEvents _contentEvents;
private CurrentContentContext _currentContentContext;
// Called during application initialization
public void Initialize(InitializationEngine context)
{
_contentEvents = context.Services.GetRequiredService<IContentEvents>();
_currentContentContext = context.Services.GetRequiredService<CurrentContentContext>();
// Subscribe to content creation events
_contentEvents.CreatedContent += CreatedContent;
_contentEvents.CreatingContent += CreatingContent;
}
// Triggered before content is created
private void CreatingContent(object sender, ContentEventArgs e)
{
// Gets the content the editor is currently viewing when the create action is initiated
var currentContentLink = _currentContentContext.ContentLink;
// ContentLink is not yet assigned at this stage
var newlyCreatedContentLink = e.ContentLink; // null
}
// Triggered after content has been created
private void CreatedContent(object sender, ContentEventArgs e)
{
// ContentLink is now assigned to the newly created content
var newlyCreatedContentLink = e.ContentLink;
// Still possible to access the original content context (where the action was initiated)
var currentContentLink = _currentContentContext.ContentLink;
}
// Called during application shutdown
public void Uninitialize(InitializationEngine context)
{
// Unsubscribe from events to prevent memory leaks
_contentEvents.CreatedContent -= CreatedContent;
_contentEvents.CreatingContent -= CreatingContent;
}
}The current content context is also useful in any metadata-aware component, such as an EditorDescriptor.
public class OfferPage : PageData
{
[EditorDescriptor(EditorDescriptorType = typeof(CollectionEditorDescriptor<OfferDetailsItem>))]
public virtual IList<OfferDetailsItem> OfferDetailsItems { get; set; }
}
public class OfferDetailsItem
{
[Display(Order = 1)]
[UIHint("test")]
public virtual string Label { get; set; }
}
[PropertyDefinitionTypePlugIn]
public class OfferDetailsItemPropertyList : PropertyList<OfferDetailsItem>
{ }
[EditorDescriptorRegistration(TargetType = typeof(string), UIHint = "test")]
public class CustomXhtmlDescriptor(CurrentContentContext currentContentContext) : StringEditorDescriptor
{
public override void ModifyMetadata(ExtendedMetadata metadata, IEnumerable<Attribute> attributes)
{
base.ModifyMetadata(metadata, attributes);
var ownerContent = metadata.FindOwnerContent(); // --> will return null because the object we annotate is not ContentData but simple POCO
var currentContent = currentContentContext.ContentLink; // --> will return correct page id
}
}