Sitecore基于条件取消发布:发布项弹窗空引用异常求助
Got it, let's break down your problem and fix it step by step:
Why the Null Reference Exception Happens
The core issue is that Sitecore.Context.ClientPage only exists in a front-end request context (like when you're interacting with the Content Editor via a browser request). The publish pipeline runs in a background thread/process, where there's no active client request context. That means Sitecore.Context.ClientPage is null when your processor runs, so calling ClientResponse.Alert() throws a null reference error.
Better Implementation Options
Option 1: Intercept the Publish Request Before It Starts (Recommended)
Instead of validating mid-publish, add your check when the user clicks the "Publish" button in the Content Editor. This gives immediate feedback and avoids context issues entirely.
- Create a custom publish command that overrides the default behavior:
using Sitecore.Data.Items; using Sitecore.Shell.Applications.ContentManager; using Sitecore.Web.UI.Sheer; namespace YourNamespace { public class ValidatingPublishCommand : PublishCommand { public override void Execute(CommandContext context) { // Get the selected item from the Content Editor Item targetItem = context.Items.FirstOrDefault(); if (targetItem == null) { SheerResponse.Alert("No item selected for publishing."); return; } // Run your custom validation logic if (!IsItemValidForPublish(targetItem)) { SheerResponse.Alert("Required fields are missing - cannot publish this item."); return; } // Validation passed: proceed with the default publish flow base.Execute(context); } private bool IsItemValidForPublish(Item item) { // Replace this with your actual validation logic // Example: Check for a required field or mandatory child items return !string.IsNullOrEmpty(item["RequiredField"]) && item.Children.Any(); } } }
- Replace the default publish command with your custom one by adding a config patch (create a file in
App_Config/Include):
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/"> <sitecore> <commands> <command name="item:publish"> <patch:attribute name="type">YourNamespace.ValidatingPublishCommand, YourAssemblyName</patch:attribute> </command> </commands> </sitecore> </configuration>
This approach is better for user experience because validation happens instantly when the button is clicked, not after the publish process has already started.
Option 2: Handle Validation in the Publish Pipeline (For Background/Server-Side Scenarios)
If you must validate during the publish pipeline (e.g., your check depends on publish-specific context data), you can't use client-side alerts directly. Instead:
- Log the error to Sitecore's logs and add it to the publish report so users can see it after publishing:
using Sitecore.Diagnostics; using Sitecore.Publishing.Pipelines.PublishItem; namespace YourNamespace { public class CheckRequiredChildItems : PublishItemProcessor { public override void Process(PublishItemContext context) { Assert.ArgumentNotNull(context, "context"); // Run your validation logic if (!IsItemValid(context.Item)) { string errorMessage = $"Validation failed for item {context.Item.Name} ({context.Item.ID}): Required fields are missing."; // Log the error to Sitecore's log files Log.Error(errorMessage, this); // Add the error to the publish report (visible in the Content Editor's publish history) context.PublishContext.Errors.Add(new Sitecore.Publishing.PublishError(context.Item, errorMessage)); // Abort the pipeline for this item (or the whole publish, depending on your needs) context.AbortPipeline(); } } private bool IsItemValid(Sitecore.Data.Items.Item item) { // Your validation logic here return item.Children.Count > 0; } } }
- Note: If you're dealing with a manual publish initiated from the Content Editor, you might be able to trigger a client alert only if the publish runs synchronously (rare in modern Sitecore versions). But this is unreliable because most publishes run asynchronously in the background. Logging and publish reports are the safe bet here.
Key Takeaways
- Avoid using
Sitecore.Context.ClientPagein publish pipelines—they run outside the client request context. - For user-initiated publishes, intercept the button click to validate upfront (Option 1 is the best choice).
- For background/server-side publishes, use logging and publish reports to communicate validation failures.
内容的提问来源于stack exchange,提问作者Deb

