在ASP.NET MVC中文件上载超过允许的大小时显示自定义错误页面

Mar*_*cus 41 c# asp.net asp.net-mvc iis-7 iis-6

我的主要问题是,当上传的文件超出允许的大小时,我想显示自定义错误页面(web.config中的maxRequestLength).

上传大文件时,在调用控制器中的上传操作方法之前会抛出HttpException.这是预料之中的.

我试图在自定义属性中捕获异常,并在控制器中覆盖OnException.为什么不能在属性或OnException方法中捕获异常?

虽然可以在global.asax中捕获Application_Error中的异常,但Response.Redirect和Server.Transfer都不能用于重定向到自定义错误页面.Server.Transfer给出"未能处理子请求"错误,而response.redirect给出"已发送Http头"错误.

有任何想法吗?

提前致谢!

马库斯

Mar*_*cus 58

在IIS7及更高版本下运行时,还有另一个参数:

<system.webServer>
  <security>
    <requestFiltering>
      <requestLimits maxAllowedContentLength="10485760" />
    </requestFiltering>
  </security>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)

默认设置略小于30 MB.

对于大小介于maxRequestLengthmaxAllowedContentLengthIIS7 之间的上传文件,将HttpException使用HTTP代码500和消息文本Maximum request length exceeded.抛出此异常时,IIS7会立即终止连接.因此HttpModule,只有在global.asax.cs中HttpException处理和清除(使用Server.ClearError())in时Application_Error(),才会重定向此错误.

对于大小超过maxAllowedContentLengthIIS7的上传文件,将显示错误代码为404和subStatusCode13的详细错误页面.错误页面可以在C:\ inetpub\custerr\en-US\404-13.htm中找到

对于IIS7上此错误的重定向,我建议httpErrors改为重定向.要重定向到不同的操作,请设置maxAllowedContentLengthmaxRequestLengthweb.config中更小的值,并将以下内容添加到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>
Run Code Online (Sandbox Code Playgroud)

  • 404.13错误需要responseMode ="Redirect".它在ExecuteURL模式下无法正常工作. (2认同)