You can't send requests that are larger than the maxContentLength
setting. The web server will kill this request much before it had even chance to reach your application and give you the possibility to handle this error. So if you want to handle it you will have to increase the value of maxContentLength
to a reasonably large number and then inside your controller action check for the ContentLength
of the uploaded file.
[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);
}
...
}
But obviously a much cleaner solution is to directly handle this at your view model. You don't need a HttpPostedFileBase argument. That's what view models are intended for:
public class MyViewModel
{
[MaxFileSize(MAX_ALLOWED_SIZE)]
public HttpPostedFileBase Document { get; set; }
... some other properties and stuff
}
where MaxFileSize is obviously a custom attribute that you could easily implement.
And now your POST action becomes more standard:
[HttpPost]
public ActionResult MyAction(MyViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
...
}
You may take a look at the following example I wrote.