Fileupload大文件大小错误处理

时间:2016-06-27 09:13:59

标签: c# asp.net

我的web.config设置如下:

<httpRuntime maxRequestLength="5000" executionTimeout="120"/>

我在Global.asax中的错误处理代码:

void Application_Error(object sender, EventArgs e)
{
    // Code that runs when an unhandled error occurs
    //Exception ex;

    string sourcepath = System.IO.Path.GetFileName(Request.Path);
    if (string.Compare(System.IO.Path.GetFileName(Request.Path), "vendorMassUpload.aspx", StringComparison.OrdinalIgnoreCase) == 0)
    {
        System.Exception lastException = Server.GetLastError();
        HttpException httpException = (HttpException)lastException;
        int httpCode = httpException.GetHttpCode();
        int errorCode = httpException.ErrorCode;
        if (errorCode == -2147467259)
        {
            Server.ClearError();
            Response.Redirect("~/vendorManagement/vendorMassUpload.aspx?fileTooLarge=true");
        }
    }
}

我在测试中用来上传的文件大小是4999 KB。 它会到达Response.Redirect,但它只会在Internet Explorer中显示This page can’t be displayed

如果throw new Exception("testing exception"); ButtonUpload_Clickif (errorCode == -2147467259)评论This page can’t be displayed,那么一切正常。

出了什么问题?

我想要做的就是重定向用户,并在上传大文件时向他们展示自定义消息,而不是告诉他们'in_same_term' => true

1 个答案:

答案 0 :(得分:0)

通常当上传的文件大小超过maxRequestLength时,web.config文件中的限制将返回HttpException,因此您可以尝试基于异常消息的重定向处理:

void Application_Error(object sender, EventArgs e)
{
    string sourcepath = System.IO.Path.GetFileName(Request.Path);
    if (string.Compare(System.IO.Path.GetFileName(Request.Path), "vendorMassUpload.aspx", StringComparison.OrdinalIgnoreCase) == 0)
    {
        System.Exception lastException = Server.GetLastError();
        HttpException httpException = (HttpException)lastException;
        int httpCode = httpException.GetHttpCode();
        int errorCode = httpException.ErrorCode;

        // check if returned exception contains "exceed"
        if (lastException != null && lastException is HttpException && lastException.Message.Contains("exceed"))
        {
            Server.ClearError();
            // redirect to custom error page
            Response.Redirect("~/vendorManagement/vendorMassUpload.aspx?fileTooLarge=true");
        }
    }
}

希望这可能有帮助,CMIIW。