我关注了这个tutorial在 HttpPostedFileBase
上创建验证,如果我使用 HttpPostedFileBase
就可以了,但如果我改为 IEnumerable<HttpPostedFileBase>
如需上传多个文件,请提交表单ModelState.IsValid
总是假的。我上传了 .png 文件,大小为 914 字节。如何使用数据标注来验证多个文件上传?
我的模型
public class BillingViewModel
{
[Required]
public long BillingID { get; set; }
public IEnumerable<TimeKeeper> TimeKeepers { get; set; }
[Required]
[ValidateFile]
public IEnumerable<HttpPostedFileBase> PostedFiles { get; set; }
}
验证文件.cs:
public class ValidateFileAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
int MaxContentLength = 1024 * 1024 * 3; //3 MB
string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
var file = value as HttpPostedFileBase;
if (file == null)
{
return false;
}
else if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
{
ErrorMessage = "Please upload Your Photo of type: " + string.Join(", ", AllowedFileExtensions);
return false;
}
else if (file.ContentLength > MaxContentLength)
{
ErrorMessage = "Your Photo is too large, maximum allowed size is : " + (MaxContentLength / 1024).ToString() + "MB";
return false;
}
else
{
return true;
}
}
}
最佳答案
您似乎将该属性转换为错误的类型。
更改此:
var file = value as HttpPostedFileBase;
至:
var files = value as IEnumerable<HttpPostedFileBase>;
然后您可以迭代集合中的每个项目并验证每个文件的大小是否正确。
关于c# - 如何使用数据注释验证 IEnumerable<HttpPostedFiles>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23607480/