尝试捕获ExecutionTimeout不起作用

时间:2013-10-22 14:47:13

标签: .net vb.net file-upload executiontimeout

这个对我来说是一个痛苦的源头!我正在使用110秒的全局ExecutionTimeout来申请。一个特定页面会生成大量未处理的异常,因为它包含FileUpload控件。

现在问题是......我知道如何使用以下声明限制web.config中的文件大小和执行超时。

<httpRuntime maxRequestLength="2097152" executionTimeout="600" />

我遇到的问题就在这里:

    'Check file size
    Dim fileSize As Integer
    Try
        fileSize = FileUpload1.FileBytes.Length
    Catch ex As Exception
        'Display message to user...
        Exit Sub
    End Try

检查文件长度的过程非常频繁地引发异常,并且在上面的try, catch中没有正常捕获该异常,它似乎遵循global.asax中的应用程序级异常处理。

我很确定无法检查客户端的文件大小,我不想继续追查maxRequestLengthexecutionTimeout,我只是想看看do是在页面上捕获这些超时并显示消息。这可能吗?

编辑---

为了更好地说明此处的问题,请尝试运行以下代码(假设您的默认executionTimeout为110秒)。

    Try
        system.threading.thread.sleep(120000)
    Catch ex As Exception
        response.write("Error caught!!")
        Exit Sub
    End Try

确保关闭调试。 catch块不起作用,你最终会得到一个未处理的System.Web.HttpException: Request timed out错误,这个我还没弄明白?

1 个答案:

答案 0 :(得分:0)

原来,页面上的代码并没有直接抛出异常,因此它不会被try, catch捕获。当脚本执行时间太长时,应用程序会监视和干预,因此当在应用程序级别引发异常时,我们需要遵循global.asax。

该解决方案涉及将错误捕获到Global.asax Application_Error块中,然后response.redirecting返回到原始页面,并将错误类型附加到查询字符串。

 Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        Dim exc As Exception = Server.GetLastError
        Dim context As HttpContext = DirectCast(sender, HttpApplication).Context

        Dim uri As String = context.Request.Url.PathAndQuery

        If uri.Contains("users/account.aspx") Then
            Response.Redirect(context.Request.Url.PathAndQuery & "&err=" & exc.GetType().ToString)
        End If
End Sub

然后,您可以在页面加载中检查任何err查询字符串值,然后在页面上相应地显示错误。

相关问题