ASP.NET MVC 3:DataAnnotations.FileExtensionsAttribute不工作

问题描述:

根据MSDN文档,默认情况下FileExtensionsAttribute(.NET 4.5)应该让我只只上传JPG,JPEG,GIF和PNG文件 - 这是我想要的。

According to the MSDN documentation, by default the FileExtensionsAttribute (.NET 4.5) should allow me to only upload only jpg,jpeg,gif and png files - which is what I want.

我试着上传JPG没有属性,它的工作原理。大。然后
我添加的属性到我的视图模型。

I tried uploading a jpg without the attribute, it works. Great. Then I added the attribute to my view model..

[FileExtensions(ErrorMessage = "Please specify a valid image file (.jpg, .jpeg, .gif or .png)")]
public HttpPostedFileBase ImageFile { get; set; }

没有喜悦。验证失败和的ErrorMessage所示。最重要的是,似乎没有被指定任何允许自定义的文件扩展名的方式。
我结束了延长FileExtensionsAttribute并用自己的验证逻辑,预计其中工程。但是,为什么不这样工作?

No joy. The verification fails and the ErrorMessage is shown. On top of that there doesn't seem to be a way to specify any allowed custom file extensions. I ended up extending the FileExtensionsAttribute and using my own verification logic, which works as expected. But why doesn't this way work?

如果需要将发布整个控制器和视图。我用本实施例,作为上载逻辑的基础,但使用DataAnnotations.FileExtensionsAttribute代替Microsoft.Web.Mvc.FileExtensions .. 如何在ASP.NET MVC中上传图片?

Will post the entire controller and view if required. I used this example as a basis for the uploading logic, but using the DataAnnotations.FileExtensionsAttribute instead of Microsoft.Web.Mvc.FileExtensions.. How do I upload images in ASP.NET MVC?

使用的扩展属性进行设置。虽然根据文档

Use the Extensions property to set them. Although according to the documentation

该文件扩展名,或默认文件扩展名(.png格式
  .JPG,.JPEG,以及名为.gif),如果未设置该属性。

The file name extensions, or the default file extensions (".png", ".jpg", ".jpeg", and ".gif") if the property is not set.

您可以设置它,就像你做了的ErrorMessage 。更可能出现的问题是,它不知道如何评估是否 HttpPostedFileBase 有正确的扩展名。你需要使用MVC框架的一个或创建自己的。

You can set it just like you did the ErrorMessage. The more likely issue is that it doesn't know how to assess whether the HttpPostedFileBase has the right extension. You'll need to use the one from the MVC framework or create your own.