113

httpRuntimeアップロード関数を作成していますが、web.configで指定された最大サイズ (最大サイズが 5120 に設定) より大きいファイルで「System.Web.HttpException: 最大要求長を超えました」をキャッチする際に問題があります。私は<input>ファイルに単純なものを使用しています。

問題は、アップロード ボタンのクリック イベントの前に例外がスローされ、コードが実行される前に例外が発生することです。では、例外をキャッチして処理するにはどうすればよいでしょうか。

編集:例外は即座にスローされるため、接続が遅いためにタイムアウトの問題ではないと確信しています。

4

16 に答える 16

97

残念ながら、そのような例外をキャッチする簡単な方法はありません。私がしていることは、ページ レベルで OnError メソッドをオーバーライドするか、global.asax の Application_Error をオーバーライドしてから、Max Request の失敗かどうかを確認し、そうであればエラー ページに転送することです。

protected override void OnError(EventArgs e) .....


private void Application_Error(object sender, EventArgs e)
{
    if (GlobalHelper.IsMaxRequestExceededException(this.Server.GetLastError()))
    {
        this.Server.ClearError();
        this.Server.Transfer("~/error/UploadTooLarge.aspx");
    }
}

それはハックですが、以下のコードは私にとってはうまくいきます

const int TimedOutExceptionCode = -2147467259;
public static bool IsMaxRequestExceededException(Exception e)
{
    // unhandled errors = caught at global.ascx level
    // http exception = caught at page level

    Exception main;
    var unhandled = e as HttpUnhandledException;

    if (unhandled != null && unhandled.ErrorCode == TimedOutExceptionCode)
    {
        main = unhandled.InnerException;
    }
    else
    {
        main = e;
    }


    var http = main as HttpException;

    if (http != null && http.ErrorCode == TimedOutExceptionCode)
    {
        // hack: no real method of identifying if the error is max request exceeded as 
        // it is treated as a timeout exception
        if (http.StackTrace.Contains("GetEntireRawContent"))
        {
            // MAX REQUEST HAS BEEN EXCEEDED
            return true;
        }
    }

    return false;
}
于 2009-03-20T10:20:17.413 に答える
58

GateKiller が言ったように、maxRequestLength を変更する必要があります。アップロード速度が遅すぎる場合は、executionTimeout を変更する必要がある場合もあります。これらの設定のいずれかを大きくしすぎないように注意してください。そうしないと、DOS 攻撃を受けやすくなります。

executionTimeout のデフォルトは 360 秒または 6 分です。

httpRuntime Elementで maxRequestLength と executionTimeout を変更できます。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
        <httpRuntime maxRequestLength="102400" executionTimeout="1200" />
    </system.web>
</configuration>

編集:

それにもかかわらず例外を処理したい場合は、既に述べたように Global.asax で処理する必要があります。コード例へのリンクは次のとおりです。

于 2009-03-20T09:47:33.340 に答える
20

これを解決するには、web.configの最大リクエスト長を増やします。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
        <httpRuntime maxRequestLength="102400" />
    </system.web>
</configuration>

上記の例は、100Mbの制限用です。

于 2009-03-20T09:34:36.617 に答える
10

クライアント側の検証も必要な場合は、例外をスローする必要が少なくなるため、クライアント側のファイルサイズの検証を実装してみることができます。

注:これは、HTML5をサポートするブラウザーでのみ機能します。 http://www.html5rocks.com/en/tutorials/file/dndfiles/

<form id="FormID" action="post" name="FormID">
    <input id="target" name="target" class="target" type="file" />
</form>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>

<script type="text/javascript" language="javascript">

    $('.target').change(function () {

        if (typeof FileReader !== "undefined") {
            var size = document.getElementById('target').files[0].size;
            // check file size

            if (size > 100000) {

                $(this).val("");

            }
        }

    });

</script>

于 2011-07-05T10:56:02.760 に答える
9

こんにちは、Damien McGivern が言及したソリューションです。IIS6 でのみ動作します。

IIS7 および ASP.NET 開発サーバーでは機能しません。「404 - ファイルまたはディレクトリが見つかりません」というページが表示されます。

何か案は?

編集:

わかりました... このソリューションは ASP.NET 開発サーバーではまだ機能しませんが、私の場合、IIS7 で機能しない理由がわかりました。

その理由は、IIS7 には組み込みの要求スキャンがあり、デフォルトで 30000000 バイト (30MB よりわずかに少ない) に設定されているアップロード ファイルの上限を課すためです。

そして、Damien McGivern が言及したソリューションをテストするために、サイズ 100 MB のファイルをアップロードしようとしていました (maxRequestLength="10240" つまり、web.config で 10MB)。ここで、サイズが 10 MB を超え 30 MB 未満のファイルをアップロードすると、ページは指定されたエラー ページにリダイレクトされます。しかし、ファイル サイズが 30MB を超えると、「404 - ファイルまたはディレクトリが見つかりません」という見苦しい組み込みエラー ページが表示されます。

したがって、これを回避するには、最大値を増やす必要があります。IIS7 で Web サイトに許可されるリクエスト コンテンツの長さ。これは、次のコマンドを使用して実行できます。

appcmd set config "SiteName" -section:requestFiltering -requestLimits.maxAllowedContentLength:209715200 -commitpath:apphost

上限を設定しました。コンテンツの長さは 200MB まで。

この設定を行った後、100MB のファイルをアップロードしようとすると、ページは正常にエラー ページにリダイレクトされます。

詳細については、http://weblogs.asp.net/jgalloway/archive/2008/01/08/large-file-uploads-in-asp-net.aspxを参照してください。

于 2010-07-07T12:22:55.960 に答える
8

これは、「ハック」を含まない別の方法ですが、ASP.NET 4.0 以降が必要です。

//Global.asax
private void Application_Error(object sender, EventArgs e)
{
    var ex = Server.GetLastError();
    var httpException = ex as HttpException ?? ex.InnerException as HttpException;
    if(httpException == null) return;

    if(httpException.WebEventCode == WebEventCodes.RuntimeErrorPostTooLarge)
    {
        //handle the error
        Response.Write("Sorry, file is too big"); //show this message for instance
    }
}
于 2015-05-23T20:00:53.673 に答える
4

これを行う1つの方法は、上ですでに述べたようにweb.configで最大サイズを設定することです。

<system.web>         
    <httpRuntime maxRequestLength="102400" />     
</system.web>

次に、アップロードイベントを処理するときに、サイズを確認し、特定の量を超えている場合は、それをトラップできます。

protected void btnUploadImage_OnClick(object sender, EventArgs e)
{
    if (fil.FileBytes.Length > 51200)
    {
         TextBoxMsg.Text = "file size must be less than 50KB";
    }
}
于 2012-09-14T22:12:50.923 に答える
3

IIS 7 以降:

web.config ファイル:

<system.webServer>
  <security >
    <requestFiltering>
      <requestLimits maxAllowedContentLength="[Size In Bytes]" />
    </requestFiltering>
  </security>
</system.webServer>

次に、コード ビハインドを次のようにチェックインできます。

If FileUpload1.PostedFile.ContentLength > 2097152 Then ' (2097152 = 2 Mb)
  ' Exceeded the 2 Mb limit
  ' Do something
End If

web.config の [Size In Bytes] が、アップロードするファイルのサイズよりも大きいことを確認してください。そうすれば、404 エラーは発生しません。その後、はるかに優れた ContentLength を使用して、コード ビハインドでファイル サイズを確認できます。

于 2014-06-23T11:26:12.710 に答える
3

IIS7 以降で動作するソリューション:ファイルのアップロードが ASP.NET MVC で許可されているサイズを超えたときにカスタム エラー ページを表示する

于 2010-09-24T13:07:32.757 に答える
2

ご存じのとおり、リクエストの最大長は 2 か所で設定されます

  1. maxRequestLength- ASP.NET アプリ レベルで制御
  2. maxAllowedContentLength- 下<system.webServer>、IIS レベルで制御

最初のケースは、この質問に対する他の回答でカバーされています。

THE SECOND ONEをキャッチするには、global.asax でこれを行う必要があります。

protected void Application_EndRequest(object sender, EventArgs e)
{
    //check for the "file is too big" exception if thrown at the IIS level
    if (Response.StatusCode == 404 && Response.SubStatusCode == 13)
    {
        Response.Write("Too big a file"); //just an example
        Response.End();
    }
}
于 2016-12-22T10:30:58.797 に答える
0

これを解決するには、web.config で要求の最大長と実行タイムアウトを増やします。

- 1200 より大きい最大実行タイムアウトを明確にしてください

<?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <httpRuntime maxRequestLength="102400" executionTimeout="1200" /> </system.web> </configuration>
于 2014-06-24T07:19:33.427 に答える
0

EndRequest イベントでキャッチするのはどうですか?

protected void Application_EndRequest(object sender, EventArgs e)
    {
        HttpRequest request = HttpContext.Current.Request;
        HttpResponse response = HttpContext.Current.Response;
        if ((request.HttpMethod == "POST") &&
            (response.StatusCode == 404 && response.SubStatusCode == 13))
        {
            // Clear the response header but do not clear errors and
            // transfer back to requesting page to handle error
            response.ClearHeaders();
            HttpContext.Current.Server.Transfer(request.AppRelativeCurrentExecutionFilePath);
        }
    }
于 2016-04-22T16:04:09.983 に答える
0

次の方法で確認できます。

        var httpException = ex as HttpException;
        if (httpException != null)
        {
            if (httpException.WebEventCode == System.Web.Management.WebEventCodes.RuntimeErrorPostTooLarge)
            {
                // Request too large

                return;

            }
        }
于 2019-03-25T08:06:42.773 に答える