Display custom error page when file upload exceeds allowed size in ASP.NET MVC

馋奶兔 提交于 2019-11-27 00:05:25
Marcus

When running under IIS7 and upwards there is another parameter:

<system.webServer>
  <security>
    <requestFiltering>
      <requestLimits maxAllowedContentLength="10485760" />
    </requestFiltering>
  </security>
</system.webServer>

The default setting is slightly less than 30 MB.

For uploaded files with size between maxRequestLength and maxAllowedContentLength IIS7 will throw an HttpException with HTTP code 500 and message text Maximum request length exceeded. When this exception is thrown, IIS7 kills the connection immediately. So an HttpModule that redirects on this error will only work if the HttpException is handled and cleared (using Server.ClearError()) in Application_Error() in global.asax.cs.

For uploaded files with size bigger than maxAllowedContentLength IIS7 will display a detailed error page with error code 404 and subStatusCode 13. The error page can be found in C:\inetpub\custerr\en-US\404-13.htm

For redirects on this error on IIS7 I recommend redirecting on httpErrors instead. To redirect to a different action set a smaller value for maxAllowedContentLength than maxRequestLength in web.config and also add the following to web.config:

<system.webServer>
  <httpErrors errorMode="Custom" existingResponse="Replace"> 
    <remove statusCode="404" subStatusCode="13" /> 
    <error statusCode="404" subStatusCode="13" prefixLanguageFilePath=""
       path="http://yoursite.com/Error/UploadTooLarge" responseMode="Redirect" /> 
  </httpErrors>
</system.webServer>

When running on IIS6, I solved it with a HttpModule by handling the BeginRequest and check if httpApplication.Context.Request.Length is larger than maxRequestLength.

To be able to redirect the entire request has to be read before redirecting.

See code example at this link: http://www.velocityreviews.com/forums/t97027-how-to-handle-maximum-request-length-exceeded-exception.html

user455406

The velocity eviews link was really helpful in solving the issue. As stated, the only drawback was the entire request (and file) needs to be read before the redirection can be done.

But it can be limited to run only when the page where the file upload control is present by being loaded like this

if (HttpContext.Current.Request.Url.ToString().Contains("UploadedPage.aspx") 
{
    //read and process page request
}

You need to make a custom HttpHandler that will do this for you. ASP.NET will automatically kill the connection if the upload size is too large (as you found out).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!