2012-08-15 26 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); 
    }