我想使用服务器端验证应用程序上的文件,并使用属性来验证自定义逻辑。
我有这个模型
public class FileTest {
[Required]
[DataType(DataType.Upload)]
[MaxFileSize(3 * 1024 * 1024)]
[AllowedExtensions(new string[] { ".pdf" })]
public IFormFile File { set; get; }
}
这是自定义属性
public class MaxFileSizeAttribute : ValidationAttribute
{
private readonly int _maxFileSize;
public MaxFileSizeAttribute(int maxFileSize)
{
_maxFileSize = maxFileSize;
}
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{
var file = value as IFormFile;
//var extension = Path.GetExtension(file.FileName);
//var allowedExtensions = new[] { ".jpg", ".png" };`enter code here`
if (file != null)
{
if (file.Length > _maxFileSize)
{
return new ValidationResult(GetErrorMessage());
}
}
return ValidationResult.Success;
}
public string GetErrorMessage()
{
return $"Maximum allowed file size is { _maxFileSize} bytes.";
}
}
public class AllowedExtensionsAttribute : ValidationAttribute
{
private readonly string[] _Extensions;
public AllowedExtensionsAttribute(string[] Extensions)
{
_Extensions = Extensions;
}
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{
var file = value as IFormFile;
var extension = Path.GetExtension(file.FileName);
if (!(file == null))
{
if (!_Extensions.Contains(extension.ToLower()))
{
return new ValidationResult(GetErrorMessage());
}
}
return ValidationResult.Success;
}
public string GetErrorMessage()
{
return $"This photo extension is not allowed!";
}
}
基本上,每当我发布表格
<form method="post" enctype="multipart/form-data">
<input asp-for="FileTest.File" class="form-control" multiple>
<span asp-validation-for="Definition.File" class="text-danger">
</span>
<button type=""submit">Submit</button>
</form>
页面模型
public async Task<IActionResult> OnPostAsync()
{
if(!ModelState.IsValid){
}
return Page();
}
例如,如果我上传一个excel文件,该文件不会无效,它会绕过modelstate。使用调试器不会触发自定义验证属性,它会直接跳转到Post Handler
编辑
我忘了提这是一个剃刀。在我的剃刀页面上,我只有这个
public FileTest File { get; set; }
根据@KirkLatin,此问题缺少BindProperty。如果缺少此标签,则不会触发验证属性。学到了新东西!