How can elegantly handle maxRequestLength exceptions?

In my ASP.NET MVC application (v2, if that matters) I have a page that allows the user to upload a file. I configured maxRequestLength for my application to allow files up to 25 MB. As a test, I send him a 500 MB file that throws an exception: Maximum request length exceeded. (I know this only because ELMAH catches the error and logs it.)

In my web.config, I set customErrors mode="On" with defaultRedirect , but the user is not redirected at all, they don’t even get a yellow death screen. For example, in Chrome you will see the error message: Error 101 (net::ERR_CONNECTION_RESET): Unknown error.

Is it possible to provide a more elegant user experience for this situation?

+2
source share
3 answers

To my knowledge, there is no way to gracefully handle the value of the "maxRequestLength" IIS parameter. It can’t even display the user error page (since there is no answer to the corresponding HTTP code). The only way to do this is to set maxRequestLength to some absurdly large number of kilobytes, for example 51200 (50 MB), and then check the ContentLength after the file has been downloaded (assuming the request does not time out up to 90 seconds). At this point, I can check if the file is <= 5MB and show a friendly error.

+4
source

I circumvented this issue by making the page invalid (so it won’t be sent back) if the selected file exceeds the maximum request length. This requires the presence of a custom verification control for the client side, verification of the correctness of file upload control. The following is an example of server confirmation to limit the file size to 4 MB:

 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; } } 

Download 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> 
0
source

All Articles