In my ASP.NET MVC (v2 if it matters) app, I have a page that allows the user to upload a file. I've configured the maxRequestLength for my app to allow files up to 25MB. As a test, I send it a 500MB file which throws the exception: Maximum request length exceeded.
(I only know this because ELMAH catches the error and logs it.)
In my web.config, I've set customErrors mode="On"
with a defaultRedirect
, but the user isn't redirected at all, they don't even get a yellow-screen-of-death. In Chrome, for example, you'll see the error: Error 101 (net::ERR_CONNECTION_RESET): Unknown error.
Is it possible to provide a more elegant user experience for this situation?
To my knowledge, there is no way to gracefully handle exceeding IIS's "maxRequestLength" setting. It can't even display a custom error page (since there is no corresponding HTTP code to respond to). The only way around this is to set maxRequestLength to some absurdly high number of kbytes, for example 51200 (50MB), and then check the ContentLength after the file has been uploaded (assuming the request didn't time out before 90 seconds). At that point, I can validate if the file <=5MB and display a friendly error.
http://nishantrana.wordpress.com/2009/01/19/fileupload-page-cannot-be-displayed-and-maximum-request-length-exceeded-error/
Try the last solution here, I tried it and works fine.
I got around this problem by making the page invalid (so it won't post back) if the chosen file is over the max request length. It requires having a custom validation control for the client side, validating the fileupload control.
Here is the server validation sub, for limiting file size to 4Mb:
Sub custvalFileSize_ServerValidate(ByVal s As Object, ByVal e As ServerValidateEventArgs)
'FileUpload1 size has to be under 4Mb
If (FileUpload1.PostedFile.ContentLength > 4194304) Then
e.IsValid = False
Else
e.IsValid = True
End If
End Sub
Here is the client side validation function:
function custvalFileSize_ClientValidate(src,args){
if (document.all("FileUpload1").files[0].size > 4194304){
args.IsValid = false;
} else {
args.IsValid = true;
}
}
The upload control and validation control:
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server" BackColor="#FFFFFF" BorderColor="#FF0000" BorderStyle="solid" BorderWidth="0" ClientValidationFunction="custvalFileSize_ClientValidate" ControlToValidate="FileUpload1" Display="Dynamic" EnableClientScript="true" ErrorMessage="<b>Please upload document files of 4Mb or less.</b>"
Font-Bold="false" Font-Names="Verdana, Arial, Helvetica" Font-Size="9px" ForeColor="#FF0000" OnServerValidate="custvalFileSize_ServerValidate" Text="<br/><span style='font-weight:bold;font-size:12px;'>This file is too large.<br />We can only accept documents of 4Mb or less.</span>"></asp:CustomValidator>