Skip to content

Instantly share code, notes, and snippets.

@PNergard
Created March 30, 2019 20:35
Show Gist options
  • Save PNergard/7df2636b45753a5b9a654447cf64461a to your computer and use it in GitHub Desktop.
Save PNergard/7df2636b45753a5b9a654447cf64461a to your computer and use it in GitHub Desktop.
using EPiServer;
using EPiServer.Core;
using EPiServer.SpecializedProperties;
using EPiServer.Web.Routing;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.ModelBinding;
namespace LinkItemAllowedTypes.Business.Attributes
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class LinkItemAllowedTypesAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute, IMetadataAware
{
// public Type[] allowedTypes { get; set; }
public List<string> allowedTypes { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null)
{
return null;
}
if (value is LinkItemCollection)
{
if ((value as LinkItemCollection).Count > 0)
{
foreach (var item in (value as LinkItemCollection))
{
var content = UrlResolver.Current.Route(new UrlBuilder(item.Href));
if (content != null)
{
var origanltype = content.GetOriginalType().ToString();
if (!allowedTypes.Contains(content.GetOriginalType().ToString()))
{
return new ValidationResult("Links to content of type: " + content.GetOriginalType() + " is not allowed!");
}
}
}
}
}
return ValidationResult.Success;
}
public void OnMetadataCreated(ModelMetadata metadata)
{
//throw new NotImplementedException();
}
public override bool RequiresValidationContext
{
get
{
return true;
}
}
public LinkItemAllowedTypesAttribute(Type[] types)
{
this.allowedTypes = types.Select(x => x.FullName).ToList();
}
}
}
@PNergard
Copy link
Author

PNergard commented Mar 30, 2019

A simple validation attribute that validates linkitems in a linkitemcollection property and if a item is an internal epierver content (page,image) the type of of that content is validated to the array of allowed types. If link type is not in the specified array publishing of page is blocked.

Blog post over at world: https://world.episerver.com/blogs/Per-Nergard/Dates/2019/3/allowedtypes-for-linkitem-collection/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment