React and EPiServer: Removing properties from output in EPiServer.ContentDeliveryApi

If you read my previous article React and EPiServer: Aggregated output with EPiServer.ContentDeliveryApi you saw a way of including your own aggregated data through properties in the content model classes. Since the JOS Content Serializer also has a very useful ignore attribute, ContentSerializerIgnoreAttribute, I’d love the EPiServer Content Delivery Api to have one as well.

Removing superfluous properties from EPiServer ContentDeliveryApi output

Since the EPiServer Content Delivery Api isn’t there yet, here is a small alteration to the code in the previous article making it possible.

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
  base.OnActionExecuting(filterContext);

  var jsonViewModel = Activator.CreateInstance<TJsonModel>();
  var currentPage = _pageRouteHelper.Value.Page as TModel;

  var epiModel = _contentModelMapper.Value.TransformContent(currentPage);

  foreach (var info in currentPage.GetType().GetProperties())
  {
    // Still using JOS Content Serializer attributes,
    // but you probably need to create your own.
    if (Attribute.IsDefined(info, typeof(ContentSerializerIncludeAttribute)))
    {
      epiModel.Properties.Add(info.Name, info.GetValue(currentPage));
      continue;
    }

    if (Attribute.IsDefined(info, typeof(ContentSerializerIgnoreAttribute)) &&
        epiModel.Properties.Keys.Contains(info.Name))
    {
      epiModel.Properties.Remove(info.Name);
      continue;
    }
  }

  jsonViewModel.Content = epiModel.Properties;

I refactored the foreach loop to contain two if-statements. The first one looks for the include attribute, and adds the property to the dictionary as before.

The second one on the other hand will check for Ignore-attributes and also verify that it was indeed added by EPiServer’s TransformContent method earlier. If it was, it’s safe to remove it.

Here is a short example of how to use the Ignore-attribute. Again, you may need to create your own.

[Display(Name = "Some property",
         Description = "Just some property",
         Order = 40)]
[ContentSerializerIgnore]
public virtual ContentArea ExampleArea { get; set; }