我在MVC 3 Web应用程序中具有文件上传功能,并且我正在尝试使用这些属性来验证FileSize和FileType:

[FileSize(1048576, ErrorMessage = "The image is too big. It should be up to 1MB")]
[FileType(MimeTypes.Image.Jpg, MimeTypes.Image.Jpeg, MimeTypes.Image.Png, "image/pjpeg", "image/x-png", ErrorMessage = "Your image must be a JPG/JPEG or PNG up to 1MB.")]
public HttpPostedFileBase File { get; set; }


HTML如下:

<input type="file" size="20" name="File" />
@Html.ValidationMessageFor(x => x.File)


当选择文件时,一切工作完美。但是,如果没有选择文件,则仍然会触发FileSize或FileType验证以及验证错误。如何避免这种情况,因为我不想在POST上需要文件?

最佳答案

您将必须修改FileSizeFileType自定义验证属性,以便在该值为null时不执行任何验证。例如:

public class FileSizeAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null)
        {
            // don't validate if value is null
            return null;
        }

        // TODO: do whatever validation you were supposed to do
        ...
    }
}


通过[Required]属性,您可以使该文件成为必需文件。

关于c# - MVC 3文件上传验证错误触发,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12157113/

10-12 12:20
查看更多