C# 未触发ASP.NET核心文件验证自定义属性
我想使用服务器端和使用属性的自定义逻辑验证应用程序上的文件 我有这个型号C# 未触发ASP.NET核心文件验证自定义属性,c#,html,asp.net-core,C#,Html,Asp.net Core,我想使用服务器端和使用属性的自定义逻辑验证应用程序上的文件 我有这个型号 public class FileTest { [Required] [DataType(DataType.Upload)] [MaxFileSize(3 * 1024 * 1024)] [AllowedExtensions(new string[] { ".pdf" })] public IFormFile File { set; get;
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>
根据@KirkLatin的说法,该问题缺少BindProperty。如果缺少此标记,则不会触发验证属性。学到了一些新东西 pdf文件呢?您没有将模型传递给方法吗?
公共异步任务OnPostAsync(FileTest模式)
您的文件属性上方似乎没有[BindProperty]
,因此我猜模型绑定甚至没有运行,而您的文件在OnPostSync
中是null
,对吗?@KirkLarkin谢谢这就是问题所在。。。尽管已经和razorpages合作了一段时间,我还是错过了这个。我猜是的,像这样的事情很容易错过。
public async Task<IActionResult> OnPostAsync()
{
if(!ModelState.IsValid){
}
return Page();
}
public FileTest File { get; set; }