我的问题是,如果我上传的文件超过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" />
答案 0 :(得分:0)
直接在模型属性中使用MaxFileSize
[Required]
[MaxFileSize(10 * 1024 , ErrorMessage = "Maximum allowed file size is {0} bytes")]
OR
请参阅This