C# IFormFile的数据批注,因此它只允许扩展名为.png、.jpg或.jpeg的文件

C# IFormFile的数据批注,因此它只允许扩展名为.png、.jpg或.jpeg的文件,c#,asp.net-core,asp.net-core-mvc,C#,Asp.net Core,Asp.net Core Mvc,我正在使用ASP.NET核心MVC。我需要为IFormFile提供数据批注/自定义数据批注,以检查所选/上载的文件是否为图像,图像的扩展名必须与*.png、*.jpg或*.jpeg匹配。这是视图模型 公共类ProductViewModel { [显示(Name=“Image”)] [必需(ErrorMessage=“选择图像”)] //[CheckIfItsAnImage(ErrorMessage=“所选/上载的文件不是图像”)] 公共文件{get;set;} } 使用 输入你的密码 公共类Pr

我正在使用ASP.NET核心MVC。我需要为
IFormFile
提供数据批注/自定义数据批注,以检查所选/上载的文件是否为图像,图像的扩展名必须与
*.png
*.jpg
*.jpeg
匹配。这是视图模型

公共类ProductViewModel
{
[显示(Name=“Image”)]
[必需(ErrorMessage=“选择图像”)]
//[CheckIfItsAnImage(ErrorMessage=“所选/上载的文件不是图像”)]
公共文件{get;set;}
}
使用

输入你的密码

公共类ProductViewModel
{
[显示(Name=“Image”)]
[必需(ErrorMessage=“选择图像”)]
[AllowedExtensions(新字符串[]{.jpg“,.jpeg“,.png”}]
公共文件{get;set;}
}

根据
回答。您还可以通过以下方式实现自定义数据验证:

public class AllowedExtensionsAttribute : ValidationAttribute
{
    private readonly string[] _extensions;

    public AllowedExtensionsAttribute(string[] extensions)
    {
        _extensions = extensions;
    }


    public override bool IsValid(object value)
    {
        if (value is null)
            return true;

        var file = value as IFormFile;
        var extension = Path.GetExtension(file.FileName);

        if (!_extensions.Contains(extension.ToLower()))
            return false;

        return true;
    }
}
然后在视图模型上指定错误消息:

public class ProductViewModel 
{
    [Display(Name = "Image")]
    [Required(ErrorMessage = "Pick an Image")]
    [FileExtensions("jpg,jpeg,png", ErrorMessage = "Your image's filetype is not valid.")]
    public IFormFile File { get; set; }
}

Chameera的答案非常接近,但不幸的是,内置的
文件扩展名
数据注释
只对字符串有效,而对文件无效。以下是解决方案:

public class ProductViewModel 
{
    [Display(Name = "Image")]
    [Required(ErrorMessage = "Pick an Image")]
    public IFormFile File { get; set; }

    [FileExtensions(Extensions = "jpg,jpeg")]
    public string FileName => File?.FileName;
}
public class ProductViewModel 
{
    [Display(Name = "Image")]
    [Required(ErrorMessage = "Pick an Image")]
    [FileExtensions("jpg,jpeg,png", ErrorMessage = "Your image's filetype is not valid.")]
    public IFormFile File { get; set; }
}
public class ProductViewModel 
{
    [Display(Name = "Image")]
    [Required(ErrorMessage = "Pick an Image")]
    public IFormFile File { get; set; }

    [FileExtensions(Extensions = "jpg,jpeg")]
    public string FileName => File?.FileName;
}