基本上我有一个带有文件输入的页面,允许最终用户上传一些文档。
我有一个看起来像这样的 Controller
public class MyController : Controller
{
[HttpPost]
public ActionResult MyAction(MyViewModel model, HttpPostedFileBase document)
{ .. }
}
我想要实现的是:当用户尝试上传大于 maxContentLength 设置的文件时,应将验证错误添加到 ModelState 并将用户返回到他提交的表格所在的页面。在 ExceptionFilter 中处理错误并重定向到自定义页面不是解决方案。
最佳答案
您不能发送大于 maxContentLength
设置的请求。 Web 服务器会在请求到达您的应用程序之前终止此请求,并让您有可能处理此错误。因此,如果您想处理它,您必须将 maxContentLength
的值增加到一个相当大的数字,然后在您的 Controller 操作中检查上传文件的 ContentLength
。
[HttpPost]
public ActionResult MyAction(MyViewModel model, HttpPostedFileBase document)
{
if (document != null && document.ContentLength > MAX_ALLOWED_SIZE)
{
ModelState.AddModelError("document", "your file size exceeds the maximum allowed file size")
return View(model);
}
...
}
但显然更简洁的解决方案是直接在您的 View 模型中处理它。您不需要 HttpPostedFileBase 参数。这就是 View 模型的用途:
public class MyViewModel
{
[MaxFileSize(MAX_ALLOWED_SIZE)]
public HttpPostedFileBase Document { get; set; }
... some other properties and stuff
}
其中 MaxFileSize 显然是您可以轻松实现的自定义属性。
现在您的 POST 操作变得更加标准:
[HttpPost]
public ActionResult MyAction(MyViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
...
}
你可以看看 following example我写了。
关于c# - 如何在 ASP.NET MVC 3 中限制上传的文件大小并在超出时很好地弹出 ModelState 并显示适当的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11395601/