最大文件大小验证属性在 mvc 4 中不起作用



我的问题是,如果我上传的文件超过 4 mb,则会引发异常"超出最大请求长度"。

我的要求是:应该显示验证错误消息。我不确定我是否错了。请帮我一些

谢谢

public class FileSizeAttribute : ValidationAttribute
    {
    private long _maxSize;
    /// <summary>
    /// Default constructor. defines maximum size of the file.
    /// </summary>
    public FileSizeAttribute()
    {
         _maxSize = Convert.ToInt32(ConfigurationManager.AppSettings["FileSize"]);
    }
    /// <summary>
    /// Override IsValid method to validate the decorated property
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public override bool IsValid(object value)
    {
        var file = value as HttpPostedFileBase;
        if (file == null) return true;
        return file.ContentLength <= _maxSize;
    }
    /// <summary>
    /// Override format message method to return failure message.
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    public override string FormatErrorMessage(string name)
    {
        return string.Format("The file size should not exceed {0} MB", Math.Ceiling((_maxSize / 1024f) / 1024f));
    }
}

物业模型:

     [FileSize]
    [FileTypes]
    public HttpPostedFileBase File

在 Web 配置文件中

<httpRuntime maxRequestLength="10240" targetFramework="4.5" />

直接在模型属性中使用MaxFileSize

[Required]
[MaxFileSize(10 * 1024 , ErrorMessage = "Maximum allowed file size is {0} bytes")]

看到这里

最新更新