An editor wanted a larger subtree from production imported into the test environment, so she could work with a copy of the existing pages. Fair enough. Export the pages, import the package, and get on with it. Except that some of the content had been published before we added our current validation rules. It was still there in production, but saving or publishing it again was no longer allowed (and it was too much to fix first). The import ran into the same problem.
This example adds an unchecked-by-default checkbox to the existing Optimizely CMS 11 import page. It lets an administrator skip content validation for that particular import, without turning it off for editors working elsewhere on the site. The intended use here is importing older content into a test environment, where the editor can fix it afterwards if needed.
The code below targets the ASP.NET version of CMS 11. I checked the import implementation in EPiServer.CMS.Core 11.20.11 and the administration page in EPiServer.CMS.UI.Core 11.23.7. It uses internal CMS validation types, so check those details against your installed versions. This is not a CMS 12 or CMS 13 example.
Why the import hits the validators
The built-in importer does not simply copy database rows. In the version above, DefaultDataImporter passes each content item to DefaultContentImporter, which calls IContentRepository.Save. There is an initial save for new content and further saves as the import proceeds. Publication also goes through Save, with a SaveAction; there is no separate repository Publish call involved here. Pending-publication content is handled separately, so importing a package does not mean that every item is unconditionally published.
One possible answer is SaveAction.SkipValidation. That is useful when you own the save call, but it is broader than the option I wanted here. The CMS documentation also describes it as a way to force updates to locked versions. I wanted to keep the lock and approval validators, as well as a property-level permission rule, while skipping the ordinary content rules.
The implementation therefore wraps the importer and the validation service. Outside the selected import, the wrapper delegates straight to the original service. Inside it, ordinary model validation is skipped and the explicitly protected rules are still evaluated. It does not add permissions or change the access level used by the CMS importer. In particular, this is not a guarantee that every custom authorization rule on a site is covered: any such rules implemented as validators need to be preserved explicitly too.
Keep the choice inside this import
First, a small scope based on AsyncLocal<T>. A static boolean would affect other requests. This value belongs to the execution context instead, and the disposable scope restores the previous value even if the import throws.
ImportValidationScope.cs
using System;
using System.Threading;
namespace MySite.ImportValidation
{
public static class ImportValidationScope
{
private static readonly AsyncLocal<bool> SkipValidation = new AsyncLocal<bool>();
public static bool ShouldSkipContentValidation => SkipValidation.Value;
public static IDisposable Begin(bool skipContentValidation)
{
var previous = SkipValidation.Value;
SkipValidation.Value = skipContentValidation;
return new Scope(previous);
}
private sealed class Scope : IDisposable
{
private readonly bool _previous;
private bool _disposed;
public Scope(bool previous)
{
_previous = previous;
}
public void Dispose()
{
if (_disposed)
{
return;
}
SkipValidation.Value = _previous;
_disposed = true;
}
}
}
}
The checkbox selection is stored on the current request. It is not read from an arbitrary query-string parameter, and a new request starts with the option off.
ImportValidationRequest.cs
using System.Web;
namespace MySite.ImportValidation
{
public static class ImportValidationRequest
{
private static readonly object RequestKey = new object();
public static void Capture(HttpContext context, bool skipContentValidation)
{
context.Items[RequestKey] = skipContentValidation;
}
public static bool ShouldSkipContentValidation(HttpContext context)
{
return context != null && context.Items[RequestKey] is bool skip && skip;
}
}
}
There is a small catch here: in this version, the admin page resolves IDataImporter in its request and then queues the import with ThreadPool.QueueUserWorkItem. The wrapper therefore captures the choice when it is created and opens the scope inside Import. It does not depend on finding the original HttpContext on the worker thread. Status, cancellation, the package stream and the import options are forwarded unchanged. Keep the importer transient; do not register this wrapper as a singleton.
ScopedDataImporter.cs
using System;
using System.IO;
using EPiServer.Core;
using EPiServer.Enterprise;
namespace MySite.ImportValidation
{
public sealed class ScopedDataImporter : IDataImporter
{
private readonly IDataImporter _inner;
private readonly bool _skipContentValidation;
public ScopedDataImporter(IDataImporter inner, bool skipContentValidation)
{
_inner = inner ?? throw new ArgumentNullException(nameof(inner));
_skipContentValidation = skipContentValidation;
}
public IImportStatus Status => _inner.Status;
public ITransferLog Import(Stream stream, ContentReference destinationRoot, ImportOptions options)
{
// The CMS resolves this importer on the request, but calls Import on a worker thread.
using (ImportValidationScope.Begin(_skipContentValidation))
{
return _inner.Import(stream, destinationRoot, options);
}
}
public void Abort()
{
_inner.Abort();
}
}
}
Add the checkbox to the existing page
I did something I have not done in over a decade, and created an ASP.NET PageAdapter. It lets us add the control without replacing the CMS import page. The control is created during initialization, on every request, and its value is captured in PreLoad, after postback data has been applied. Reading it in OnInit would be too early.
ImportDataPageAdapter.cs
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.Adapters;
using System.Web.UI.WebControls;
namespace MySite.ImportValidation
{
public class ImportDataPageAdapter : PageAdapter
{
private CheckBox _skipValidation;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
var uploadView = FindControl(Page, "UploadFileView");
if (uploadView == null)
{
throw new InvalidOperationException("The CMS import upload view could not be found.");
}
_skipValidation = new CheckBox
{
ID = "SkipContentValidation",
EnableViewState = false,
Text = "Skip content validation for this import (content may not meet the current rules)."
};
var row = new Panel();
row.Controls.Add(_skipValidation);
var updateExisting = FindControl(uploadView, "UpdateExistingPagesCheckBox") as CheckBox;
if (updateExisting != null)
{
row.Style[HtmlTextWriterStyle.MarginTop] = "0.5em";
var parent = updateExisting.Parent;
parent.Controls.AddAt(parent.Controls.IndexOf(updateExisting) + 1, row);
}
else
{
row.CssClass = "epi-formArea epi-paddingVertical";
uploadView.Controls.Add(row);
}
Page.PreLoad += CaptureSelection;
}
private void CaptureSelection(object sender, EventArgs e)
{
ImportValidationRequest.Capture(HttpContext.Current, _skipValidation.Checked);
}
private static Control FindControl(Control parent, string id)
{
if (parent.ID == id)
{
return parent;
}
foreach (Control child in parent.Controls)
{
var match = FindControl(child, id);
if (match != null)
{
return match;
}
}
return null;
}
}
}
Register the adapter in App_Browsers/ImportValidation.browser at the web application root:
<browsers>
<browser refID="Default">
<controlAdapters>
<adapter controlType="EPiServer.UI.Admin.ImportData, EPiServer.UI"
adapterType="MySite.ImportValidation.ImportDataPageAdapter, MySite" />
</controlAdapters>
</browser>
</browsers>
The part after the comma in adapterType is the assembly name, not another namespace. The example uses MySite for both. Change it to your web assembly name and make sure the browser file is included in the deployed application. If the file is missing, the checkbox will be missing too. The control IDs used above belong to the CMS 11 admin page and should be checked when upgrading the UI package.
Keep the rules that are not about content quality
The following attribute is a small example of a property-edit restriction. It allows a modified property only for the listed roles and also marks the field read-only in MVC metadata for other users. The server-side check is the important part; a read-only field in the editor is not authorization on its own. If your site already has a permission attribute, preserve that implementation and adapt the validation wrapper to recognize it instead of introducing a second rule.
PropertyEditRestrictionAttribute.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading;
using System.Web.Mvc;
using EPiServer.Core;
namespace MySite.ImportValidation
{
[AttributeUsage(AttributeTargets.Property)]
public class PropertyEditRestrictionAttribute : ValidationAttribute, IMetadataAware
{
public PropertyEditRestrictionAttribute(string[] allowedRoles)
{
AllowedRoles = allowedRoles ?? throw new ArgumentNullException(nameof(allowedRoles));
}
public string[] AllowedRoles { get; set; }
public void OnMetadataCreated(ModelMetadata metadata)
{
if (!Validate()) metadata.IsReadOnly = true;
}
public override string FormatErrorMessage(string name)
{
return "You do not have permission to change " + name + ".";
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var contentData = validationContext.ObjectInstance as IContentData;
if (contentData == null)
{
//This attribute only handles instances of IContentData.
return ValidationResult.Success;
}
var property = contentData.Property[validationContext.MemberName];
if (property == null)
{
return new ValidationResult("The protected property could not be checked.");
}
if (!property.IsModified)
{
return ValidationResult.Success;
}
if (Validate())
{
return ValidationResult.Success;
}
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
public override bool RequiresValidationContext => true;
public bool Validate()
{
var principal = Thread.CurrentPrincipal;
return principal != null && AllowedRoles != null
&& AllowedRoles.Any(role => !string.IsNullOrWhiteSpace(role) && principal.IsInRole(role));
}
}
}
The validation wrapper below keeps that attribute active, including on local blocks. It also runs the CMS content-lock validator and, when a save context is present, the approval-request validator. The type names are used because those two validator classes are internal in this CMS version.
ImportContentValidationService.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.CompilerServices;
using EPiServer.Core;
using EPiServer.Validation;
namespace MySite.ImportValidation
{
public sealed class ImportContentValidationService : IContextValidationService
{
private readonly IValidationService _inner;
private readonly IContextValidationService _contextInner;
internal IValidationService Inner => _inner;
public ImportContentValidationService(IValidationService inner, IContextValidationService contextInner)
{
_inner = inner ?? throw new ArgumentNullException(nameof(inner));
_contextInner = contextInner ?? inner as IContextValidationService
?? throw new ArgumentException("A context validation service is required.", nameof(inner));
}
public IEnumerable<ValidationError> Validate(object instance)
{
return ImportValidationScope.ShouldSkipContentValidation && instance is IContentData
? ValidateProtectedRules(instance, null)
: _inner.Validate(instance);
}
public IEnumerable<ValidationError> Validate<T>(object instance, T context)
{
return ImportValidationScope.ShouldSkipContentValidation && instance is IContentData
? ValidateProtectedRules(instance, context)
: _contextInner.Validate(instance, context);
}
private IEnumerable<ValidationError> ValidateProtectedRules(object instance, object context)
{
var errors = new List<ValidationError>();
ValidateAuthorization(instance as IContentData, "", new HashSet<object>(ReferenceComparer.Instance), errors);
var inner = _inner;
while (inner is ImportContentValidationService decorator)
{
inner = decorator.Inner;
}
var cms = inner as EPiServer.Validation.Internal.ValidationService;
if (cms == null)
{
throw new InvalidOperationException("Cannot preserve protected validators through an unknown validation service. Import was stopped.");
}
if (instance is IContent content)
{
// Locks and approval workflow are not content-quality rules.
foreach (var validator in cms.RegisteredValidators)
{
var rule = validator.EncapsulatedValidator;
var ruleType = rule.GetType().FullName;
if (ruleType == "EPiServer.Validation.Internal.ContentLockValidator" && rule is IValidate<IContent> locks)
{
errors.AddRange(locks.Validate(content));
}
else if (ruleType == "EPiServer.Validation.Internal.RequestApprovalValidator"
&& rule is IContextValidate<IContent, ContentSaveValidationContext> approval
&& context is ContentSaveValidationContext saveContext)
{
errors.AddRange(approval.Validate(content, saveContext));
}
}
}
return errors;
}
private static void ValidateAuthorization(IContentData content, string prefix, ISet<object> visited, ICollection<ValidationError> errors)
{
if (content == null || !visited.Add(content))
{
return;
}
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(content))
{
foreach (var restriction in property.Attributes.OfType<PropertyEditRestrictionAttribute>())
{
var context = new ValidationContext(content) { MemberName = property.Name };
// This attribute checks modification and roles, not the property's value.
var result = restriction.GetValidationResult(null, context);
if (result != ValidationResult.Success)
{
errors.Add(new ValidationError
{
Source = content,
PropertyName = prefix + property.Name,
ErrorMessage = result.ErrorMessage,
Severity = ValidationErrorSeverity.Error,
ValidationType = ValidationErrorType.AttributeMatched
});
}
}
// Local blocks are validated recursively; linked content is not loaded or traversed.
if (typeof(IContentData).IsAssignableFrom(property.PropertyType))
{
ValidateAuthorization(property.GetValue(content) as IContentData, prefix + property.Name + ".", visited, errors);
}
}
}
private sealed class ReferenceComparer : IEqualityComparer<object>
{
public static readonly ReferenceComparer Instance = new ReferenceComparer();
public new bool Equals(object x, object y) => ReferenceEquals(x, y);
public int GetHashCode(object obj) => RuntimeHelpers.GetHashCode(obj);
}
}
}
This is the part to review against your own site. Required, length checks and ordinary IValidate<T> rules are bypassed, but so are other content validators that are not explicitly retained above. A custom authorization validator must not be left in that group. Local blocks are traversed without following content references, and the reference-based set prevents a circular local-block reference from causing endless recursion.
If another decorator hides the CMS validation service, the checked import now stops instead of silently proceeding without the protected CMS validators. Normal, unchecked validation still delegates to the existing service. That is preferable to assuming that an unfamiliar wrapper is safe to ignore.
Register the wrappers
There is one CMS 11 detail worth keeping in the initialization module. The built-in validation module resolves IValidationService and casts it to its concrete implementation before populating its validators. Our decorator prevents that cast. We therefore initialize the wrapped original service explicitly, once for each distinct instance, after the CMS validation module. Otherwise it is possible to break ordinary validation as an unintended side effect of adding the import option.
ImportValidationInitialization.cs
using System.Collections.Generic;
using System.Web;
using EPiServer.Enterprise;
using EPiServer.Framework;
using EPiServer.Framework.Initialization;
using EPiServer.Framework.TypeScanner;
using EPiServer.ServiceLocation;
using EPiServer.Validation;
namespace MySite.ImportValidation
{
[InitializableModule]
[ModuleDependency(typeof(EPiServer.Validation.Internal.ValidationService))]
public class ImportValidationInitialization : IConfigurableModule
{
public void ConfigureContainer(ServiceConfigurationContext context)
{
context.Services.Intercept<IDataImporter>((locator, importer) =>
new ScopedDataImporter(importer, ImportValidationRequest.ShouldSkipContentValidation(HttpContext.Current)));
context.Services.Intercept<IValidationService>((locator, validator) =>
new ImportContentValidationService(validator, null));
context.Services.Intercept<IContextValidationService>((locator, validator) =>
new ImportContentValidationService(validator, validator));
}
public void Initialize(InitializationEngine context)
{
var locator = context.Locate.Advanced;
var initialized = new HashSet<EPiServer.Validation.Internal.ValidationService>();
// CMS 11 initializes validators only after casting IValidationService to its concrete
// implementation. Decoration prevents that cast, so initialize the originals explicitly.
InitializeOriginal(locator.GetInstance<IValidationService>(), locator, initialized);
InitializeOriginal(locator.GetInstance<IContextValidationService>(), locator, initialized);
}
private static void InitializeOriginal(IValidationService service, IServiceLocator locator,
ISet<EPiServer.Validation.Internal.ValidationService> initialized)
{
while (service is ImportContentValidationService decorator)
{
service = decorator.Inner;
}
var original = service as EPiServer.Validation.Internal.ValidationService;
if (original != null && initialized.Add(original))
{
original.Initialize(locator.GetInstance<ITypeScannerLookup>(), locator);
}
}
public void Uninitialize(InitializationEngine context) { }
}
}
The sample has no dependency on a site-specific StructureMap initialization class. If your site replaces either validation service in its own module, review the registration order and add a dependency on that module where needed. Both IValidationService and IContextValidationService are intercepted, since saves can carry a validation context.
What about validation in content events?
Some sites have content checks in saving or publishing event handlers rather than in the validation service. Those handlers still run. If a particular handler only enforces a content-quality rule that should be skipped for this import, add the following guard at the start of that handler:
if (MySite.ImportValidation.ImportValidationScope.ShouldSkipContentValidation)
{
return;
}
Keep the guard local to that rule. Do not put it at the top of a shared handler that also checks upload permissions, restricts file types for security reasons, updates indexes or performs other work. The checkbox does not disable events globally.
Putting it in the site
Place the seven C# files in the web project, for example under Business/ImportValidation, and deploy the browser registration at the root shown above. The example uses the CMS Core assemblies, System.Web, System.ComponentModel.DataAnnotations and System.Web.Mvc. A traditional .NET Framework project may require explicit project-file entries:
<ItemGroup>
<Compile Include="Business\ImportValidation\ImportValidationScope.cs" />
<Compile Include="Business\ImportValidation\ImportValidationRequest.cs" />
<Compile Include="Business\ImportValidation\ScopedDataImporter.cs" />
<Compile Include="Business\ImportValidation\ImportDataPageAdapter.cs" />
<Compile Include="Business\ImportValidation\PropertyEditRestrictionAttribute.cs" />
<Compile Include="Business\ImportValidation\ImportContentValidationService.cs" />
<Compile Include="Business\ImportValidation\ImportValidationInitialization.cs" />
<Content Include="App_Browsers\ImportValidation.browser" />
</ItemGroup>
Leave the checkbox unchecked for normal imports. For the older subtree, select it deliberately and review the import log afterwards. This does not repair the content, bypass database constraints or make the import transactional. An interrupted import can still leave partially imported items behind. Once the import scope ends, the current validation rules apply again, including when the editor later tries to publish one of the imported pages.
For this case, that was the useful distinction: get the old content into the test environment so the editor can work on it, without relaxing the rules for the rest of the site.