Basically I have a page with a file input that allows end-users to upload some document.
I have a controller which looks like this
public class MyController : Controller
{
[HttpPost]
public ActionResult MyAction(MyViewModel model, HttpPostedFileBase document)
{ .. }
}
What I want to achieve is: when a user attempts to upload a file that is larger than the maxContentLength setting allows a validation error should be added to the ModelState and the user should be returned to the page where the form he submitted was. Handling the error in an ExceptionFilter and redirecting to a custom page isn’t a solution.
You can’t send requests that are larger than the
maxContentLengthsetting. 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 ofmaxContentLengthto a reasonably large number and then inside your controller action check for theContentLengthof the uploaded file.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:
where MaxFileSize is obviously a custom attribute that you could easily implement.
And now your POST action becomes more standard:
You may take a look at the following example I wrote.