Reporting Max Request Length Exceeded in an ASP.NET MVC view
I am using a custom HTTPModule to check the size of the request being posted. If it is larger than a given size I would like to stop the request but still render the view with an appropriate error message.
I want to make it nice an开发者_StackOverflow社区d simple to reuse so in my action perhaps having a ValidationAttribute on the model?
Has anyone done this before and have any pointers?
The issue is that there are parts of the request which may be required to display the page, so stopping the whole request means that you may not be able to display the view.
In our case this was using the ValidateAntiForgeryTokenAttribute, this would throw an exception because you went to the action and the request didn't contain the required data.
There are a few solutions which strip out the files from the request, which means that asp.net doesn't run out of memory, but this means that you are still dealing with the incoming stream and you have to put a limit on this somewhere
<!-- Max 4MB -->
<httpRuntime maxRequestLength="4960"/>
This is where you tell asp.net to throw a wobbly and not deal with the request, you can then catch the 413 error in the usual way and show an error page, or what ever. (the above is the default afaik)
What we have done here is to add another setting, MaxContentLength, above this value and below "the wobbly" we can say "its too big" by checking the Request.ContentLength in a base controller and set a model error
if (Request.ContentLength
> Settings.Default.MaxContentLength * 1024) {
ModelState.AddModelError("_Form", Resources.MaximumSizeRequestExceeded);
}
Now Model.IsValid will be false in my action
This is not ideal, but with some explanatory text with size limits in... its workable
精彩评论