Как отловить ConfigurationErrorsException за нарушение maxRequestLength?

Я ограничиваю размер файла, который пользователи могут загружать на сайт с Web.config. Как объяснено здесь , оно должно вызвать исключение ConfigurationErrorsException, если размер не принят. Я пытался поймать его из метода действия или контроллера для запросов на загрузку, но не повезло. Соединение сброшено, и я не могу показать страницу ошибки.

Я пытался поймать его в событии BeginRequest, но независимо от того, что я делаю, исключение не обрабатывается. Вот код:

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    HttpContext context = ((HttpApplication)sender).Context;
    try
    {
        if (context.Request.ContentLength > maxRequestLength)
        {
            IServiceProvider provider = (IServiceProvider)context;
            HttpWorkerRequest workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));

            // Check if body contains data
            if (workerRequest.HasEntityBody())
            {
                // get the total body length
                int requestLength = workerRequest.GetTotalEntityBodyLength();
                // Get the initial bytes loaded
                int initialBytes = 0;
                if (workerRequest.GetPreloadedEntityBody() != null)
                    initialBytes = workerRequest.GetPreloadedEntityBody().Length;
                if (!workerRequest.IsEntireEntityBodyIsPreloaded())
                {
                    byte[] buffer = new byte[512];
                    // Set the received bytes to initial bytes before start reading
                    int receivedBytes = initialBytes;
                    while (requestLength - receivedBytes >= initialBytes)
                    {
                        // Read another set of bytes
                        initialBytes = workerRequest.ReadEntityBody(buffer, buffer.Length);

                        // Update the received bytes
                        receivedBytes += initialBytes;
                    }
                    initialBytes = workerRequest.ReadEntityBody(buffer, requestLength - receivedBytes);
                }
            }
        }
    }
    catch(HttpException)
    {
        context.Response.Redirect(this.Request.Url.LocalPath + "?action=exception");
    }
}

Но я все еще получаю это:

Maximum request length exceeded.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Web.HttpException: Maximum request length exceeded.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Обновление:

Какой метод вызывает исключение в любом случае? Если я читаю запрос, он вызывает исключение. Если я его вообще не читаю, в браузере появляется сообщение «101 Connection Reset». Что здесь можно сделать?

10
задан Ufuk Hacıoğulları 1 October 2011 в 09:35
поделиться

1 ответ

Вы не можете отловить ошибку в методе действия, потому что исключение возникает раньше, но вы можете отловить его здесь

protected void Application_Error() {
     var lastError = Server.GetLastError();
     if(lastError !=null && lastError is HttpException && lastError.Message.Contains("exceed")) {
      Response.Redirect("~/errors/RequestLengthExceeded");
      }
    }   

Фактически, когда размер файла превышает пределы, возникает ошибка HttpException.

Существует также ограничение IIS на контент, который нельзя уловить в приложении. IIS 7 выдает

Ошибка HTTP 404.13 - не найдено. Модуль фильтрации запросов настроен на отклонение запроса, длина которого превышает длину содержимого запроса.

Вы можете погуглить, там много информации об этой ошибке iis.

5
ответ дан 4 December 2019 в 03:16
поделиться
Другие вопросы по тегам:

Похожие вопросы: