2012-08-15 52 views
1

我放在web.config中的以下行,以禁止超过2 MB的更大的文件上传:在ASP.NET页面处理异常的ProcessRequest中

<httpRuntime maxRequestLength="2048" /> 

当我打的页面(其中有一个FileUpload控件)并上传一个大于2MB的文件,该页面将在ProcessRequest(下面的Callstack)中引发异常。我试着重载ProcessRequest,并且我可以处理catch块中的异常。问题是,当然,在ProcessRequest期间,我的页面中的控件尚未实例化。

我的问题是:有没有办法处理异常的方式,我可以将消息返回给页面供用户查看,或者以某种方式允许请求通过(以某种方式删除文件)它到达Page_Load并进行正常处理?

调用堆栈:

at System.Web.UI.Page.HandleError(Exception e) 
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) 
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) 
at System.Web.UI.Page.ProcessRequest() 
at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) 
at System.Web.UI.Page.ProcessRequest(HttpContext context) 
at MyWebsite2.DocDashboard.ProcessRequest(HttpContext req) in MyFile.aspx.cs:line 28 
+1

与论坛网站不同,我们不使用“谢谢”或“任何帮助赞赏”,或在[so]上签名。请参阅“[应该'嗨','谢谢',标语和致敬从帖子中删除?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be -removed-from-posts)。此外,FYI,这是ASP.NET,而不是ASP。 – 2012-08-15 01:21:30

回答

1

我终于能够解决的问题。我无法在网上找到任何有关它的信息,所以我正在分享我的解决方案。就我个人而言,我并不喜欢这个解决方案,但这是我发现的唯一工作。为避免崩溃,请覆盖虚拟函数ProcessRequest,并在文件超过大小限制时从流中使用该文件。然后调用基地,它会处理该页面就好了,文件被删除。这里是代码:

 public virtual void ProcessRequest(HttpContext context) 
    { 
     int BUFFER_SIZE = 3 * 1024 * 1024; 
     int FILE_SIZE_LIMIT = 2 * 1024 * 1024; 
     if (context.Request.Files.Count > 0 && 
        context.Request.Files[0].ContentLength > FILE_SIZE_LIMIT) 
     { 
      HttpPostedFile postedFile = context.Request.Files[0]; 
      Stream workStream = postedFile.InputStream; 
      int fileLength = postedFile.ContentLength; 
      Byte[] fileBuffer = new Byte[BUFFER_SIZE]; 
      while (fileLength > 0) 
      { 
       int bytesToRead = Math.Min(BUFFER_SIZE, fileLength); 
       workStream.Read(fileBuffer, 0, bytesToRead); 
       fileLength -= bytesToRead; 
      } 

      workStream.Close(); 
     } 


     base.ProcessRequest(context); 
    }