gpt4 book ai didi

c# - 如何使用数据注释验证 IEnumerable

转载 作者:太空宇宙 更新时间:2023-11-03 10:45:25 26 4
gpt4 key购买 nike

我关注了这个tutorialHttpPostedFileBase 上创建验证,如果我使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com