Модуль ASP NET Http не получает больших запросов до исключения - PullRequest
0 голосов
/ 01 марта 2019

После поиска подходящего способа обработки больших запросов в ASP NET, чтобы избежать показа сообщения об ошибке по умолчанию maxRequestLength, превышенного для пользователя, я прочитал, что HttpModule может работать для этого.Я создал следующий HttpModule, но он все еще не может получить запрос до того, как ASP NET покажет страницу с ошибкой.Может быть, кто-то мог бы указать мне правильное направление:

public class ApplicationLargeRequestsHttpModule : IHttpModule
{
    public void Dispose()
    {
        //throw new NotImplementedException();
    }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += Application_LargeRequestsHandler;
    }

    private void Application_LargeRequestsHandler(object sender, EventArgs e)
    {
        var httpRuntimeSection = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;

        int maxRequestLength = 0;

        if (httpRuntimeSection != null)
        {
            maxRequestLength = httpRuntimeSection.MaxRequestLength;
        }

        int maxRequestLengthSafeRange = 80;

        int maxSafeRequestLength = maxRequestLength - (maxRequestLength * (maxRequestLengthSafeRange / 100));

        bool safeRequestLengthExceeded = HttpContext.Current.Request.ContentLength > maxSafeRequestLength;

        Uri requestUrl = HttpContext.Current.Request.Url;

        string hostName = requestUrl.Authority.ToLower();

        if (safeRequestLengthExceeded)
        {
            HttpContext.Current.Response.Redirect(url: requestUrl.GetLeftPart(UriPartial.Authority) + "/Dashboard/CargaFallida");
            HttpContext.Current.Response.End();
        }
    }
}

РЕДАКТИРОВАТЬ

Через некоторое время я реорганизовал свой код, чтобы обнаружить ответ кода состояния 404.13, которыйсрабатывает на MaxRequestLengthExceeded, но сейчас перенаправление - это моя проблема.Если я использую HttpContext.Current.Response.Redirect, я сохраняю проблему, после поиска соответствующего вопроса я изменил его на HttpContext.Current.Server.Transfer, но он выдает «Ошибка выполнения дочернего запроса для пути ...».Как я мог справиться с этим?

public class ApplicationLargeRequestsHttpModule : IHttpModule
    {
        public void Dispose()
        {
            //throw new NotImplementedException();
        }

        public void Init(HttpApplication context)
        {
            context.EndRequest += Application_LargeRequestsHandler;
        }

        /// <summary>
        /// Handler for 404.13 Responses handled by RequestFilteringModule. Protection
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Application_LargeRequestsHandler(object sender, EventArgs e)
        {
            var responseStatusCode = HttpContext.Current.Response.StatusCode;

            var responseSubStatusCode = HttpContext.Current.Response.SubStatusCode;

            bool safeRequestLengthExceeded = responseStatusCode == (int)HttpStatusCode.NotFound 
                && responseSubStatusCode == 13;

            var httpRuntimeSection = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;

            int maxRequestLength = 0;

            if (httpRuntimeSection != null)
            {
                maxRequestLength = httpRuntimeSection.MaxRequestLength;
            }


            var requestUrl = HttpContext.Current.Request.Url;      

            if (safeRequestLengthExceeded)
            {
                HttpContext.Current.Server.Transfer(path: requestUrl.LocalPath);
                //HttpContext.Current.Response.End();
            }
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...