在 ASP.NET 页中处理进程请求中的异常



我在web.config中放置了以下行,以禁止上传大于2 MB的文件:

<httpRuntime maxRequestLength="2048" />

当我点击页面(具有FileUpload控件)并上传大于2 MB的文件时,该页面将在ProcessRequest期间引发异常(下面的调用堆栈)。 我尝试重载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

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

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

最新更新