ASP.NET RC2 IFormFile文件扩展名和文件最大大小自定义验证

时间:2016-07-22 14:04:57

标签: asp.net-mvc asp.net-core-mvc unobtrusive-validation .net-core-rc2

我想在MVC-6 RC2中使用自定义jquery不显眼的验证器

Old Answer类似,我在This one 中看到了一些RC2示例,但我不知道如何为文件实现它。

这是我的观看模式

public class FileUploadViewModel
    {
        //TODO [FileType(Validtype="jpeg,png,jif", MaxSize=112222)]// this is what I want
        [Required(ErrorMessage = "Please select a file")]
        public IFormFile File { get; set; }

        [Required(ErrorMessage = "Please select link")]
        public string FileName { get; set; }

        public string ExternalLink { get; set; }

        public string Description { get; set; }    
    }

1 个答案:

答案 0 :(得分:2)

我最终通过使用属性来解决我的问题

以下是我创建它的方式。 (通过我们的应用程序,我的大小和扩展名是静态的,这就是为什么我在FileTypeAttribute中对其进行硬编码,但是如果你愿意,可以将它设置为动态并将其传递给属性构造函数。

onClick(event){
    let _to = event.??
}

<Link onClick={this.onClick} to={'/about'}>about</Link>

然后在我的视图模型中,我使用如下属性

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class FileTypeAttribute : ValidationAttribute, IClientModelValidator
    {
        private const int MaxSize = 1048576;
        private const string _DefaultErrorMessage = "Only the following file types are allowed: {0}";
        private IEnumerable<string> _ValidTypes { get; set; }

        public string ValidTypes { get; set; }

        public string ErrorMessageExtension { get; set; }

        public string ErrorMessageSize { get; set; }


        public FileTypeAttribute(string errorExtension, string errorSize)
        {
            ILang lang = ((ContextServiceImpl)ContextService.Instance).HttpContext.RequestServices.GetService(typeof(ILang)) as ILang;
            ErrorMessageExtension = lang[errorExtension];
            ErrorMessageSize = lang[errorSize];

        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            IFormFile file = value as IFormFile;
            if (file != null)
            {

                if (!_ValidTypes.Any(e => file.FileName.EndsWith(e)))
                {
                    return new ValidationResult(ErrorMessageExtension);
                }
                if (file.Length > MaxSize)
                {
                    return new ValidationResult(ErrorMessageSize);
                }
            }

            return ValidationResult.Success;
        }

        public void AddValidation(ClientModelValidationContext context)
        {
            MergeAttribute(context.Attributes, "data-val", "true");
            var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
            MergeAttribute(context.Attributes, "data-val-fileextensions", ErrorMessageExtension);
            MergeAttribute(context.Attributes, "data-val-maxfilesize", ErrorMessageSize);
        }

        private bool MergeAttribute(
        IDictionary<string, string> attributes, string key, string value)
        {
            if (attributes.ContainsKey(key))
            {
                return false;
            }

            attributes.Add(key, value);
            return true;
        }
    }

然后在javascript中执行此操作

public class FileUploadViewModel
    {
         [FileType("invalid format", "invalid size")]
        [Required(ErrorMessage = "Please select a file")]
        public IFormFile File { get; set; }

        [Required(ErrorMessage = "Please select link")]
        public string FileName { get; set; }

        public string ExternalLink { get; set; }

        public string Description { get; set; }    
    }