Episerver:如何验证图片类型ContentReference仅允许.ico文件?
问题:限制ContentReference字段仅允许上传.ico格式文件
我有一个标记为UIHint.Image的ContentReference字段,当前支持包括.ico在内的所有图片类型。需要验证此字段,使用户仅能上传.ico格式的文件。目前即使使用了仅匹配.ico文件的正则表达式,验证仍失败,我已确认正则表达式本身可正确匹配.ico文件,附上代码片段:
[Display(GroupName = Global.GroupNames.SiteSettings, Name = "Favicon", Description = "", Order = 20)]
[UIHint(UIHint.Image)]
[RegularExpression("[^\s]+(.*?)\.(ico)$", ErrorMessage = "Only .ico extension allowed")]
public virtual ContentReference Favicon { get; set; }
解决方案
- 问题根源:
RegularExpression特性直接作用于ContentReference时,匹配的是内容的GUID引用而非上传文件的文件名,所以正则完全起不到验证作用。 - 正确做法是自定义验证特性,通过
ContentReference获取对应的媒体内容,再检查文件扩展名:
- 自定义验证特性代码:
public class AllowedFileExtensionAttribute : ValidationAttribute { private readonly string[] _allowedExtensions; public AllowedFileExtensionAttribute(params string[] allowedExtensions) { _allowedExtensions = allowedExtensions.Select(e => e.ToLower()).ToArray(); } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value is ContentReference contentReference && !ContentReference.IsNullOrEmpty(contentReference)) { var contentLoader = validationContext.GetService<IContentLoader>(); if (contentLoader.TryGet<IContent>(contentReference, out var content)) { if (content is IMediaData mediaData) { var fileExtension = Path.GetExtension(mediaData.BinaryData.FileName).ToLower(); if (!_allowedExtensions.Contains(fileExtension)) { return new ValidationResult(ErrorMessage ?? $"仅允许上传{string.Join(", ", _allowedExtensions)}格式的文件"); } } } } return ValidationResult.Success; } }
- 将自定义特性应用到目标字段:
[Display(GroupName = Global.GroupNames.SiteSettings, Name = "Favicon", Description = "", Order = 20)] [UIHint(UIHint.Image)] [AllowedFileExtension(".ico", ErrorMessage = "仅允许上传.ico格式的文件")] public virtual ContentReference Favicon { get; set; }
- 补充说明:该方法直接检查媒体文件的实际扩展名,比正则表达式更可靠,同时还能过滤掉非媒体类型的内容引用。
内容的提问来源于stack exchange,提问作者Mss
相关产品推荐
相关产品推荐

