How to handle ""Maximum request length exceeded" exception

In global.asax:

protected void Application_BeginRequest(Object sender, EventArgs e) { HttpRuntimeSection runTime = (HttpRuntimeSection)WebConfigurationManager.GetSection("system.web/httpRuntime"); //Approx 100 Kb(for page content) size has been deducted because the maxRequestLength proprty is the page size, not only the file upload size int maxRequestLength = (runTime.MaxRequestLength - 100) * 1024;

//This code is used to check the request length of the page and if the request length is greater than 
//MaxRequestLength then retrun to the same page with extra query string value action=exception

HttpContext context \= ((HttpApplication)sender).Context;
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[512000]; // 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); } } // Redirect the user to the same page with querystring action=exception.  context.Response.Redirect("~/Erros/FicheiroGrande.aspx"); } }

This article is part of the GWB Archives. Original Author: Sglima

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.