FileUpload : Page Cannot be displayed and maximum request length exceeded error


By default, ASP.NET permits only files that are 4,096 kilobytes (KB) or less to be uploaded to the Web server.  To upload larger files, we must change the maxRequestLength parameter of the <httpRuntime> section in the Web.config file. By default, the <httpRuntime> element is set to the following parameters in the Machine.config file:

<httpRuntime

executionTimeout=90

maxRequestLength=4096

useFullyQualifiedRedirectUrl=false

minFreeThreads=8

minLocalRequestFreeThreads=4

appRequestQueueLimit=100

/>

We can change the value of maxRequestLength to a desired value in our web.config of the application. For 10 mb we can set it to 10240 KB. Even in this case if user tries to upload a file with size more than 10 mb we than get the above “Page cannot be displayed error ” or the page simply hang up. In this case we can catch the error in the Application_Error event handler of the Global.asax file.

void Application_Error(object sender, EventArgs e)

{

if (System.IO.Path.GetFileName(Request.Path) == “Default.aspx”)

{

System.Exception appException = Server.GetLastError();

if (appException.InnerException.Message == “Maximum request length exceeded.”)

{

Server.ClearError();

Response.Write(“The form submission cannot be processed because it exceeded the maximum length allowed by the Web administrator. Please resubmit the form with less data.”);

Response.Write(“<BR><a href=’Default.aspx’>Click Here to go back to page</a> </BR>”);

Response.End();  } } }

I tried with the above code, but it isn’t consistent.

The best solution for this could be to set the value of maxRequestLength to a very high value.

and checking in the code for the size.

Say changing the value to say 700mb ( not sure what the maximum length of request could be)

<httpRuntime useFullyQualifiedRedirectUrl=true

maxRequestLength=716800

/>

And checking for the length in your code

// Putting the constraint of 1 mb

if (FileUpload1.FileContent.Length < 1024){

FileUpload1.SaveAs(@”C:/MyFolder/” + FileUpload1.FileName);}

else{

return;}

At least the above solution would save us from the page not displayed error.

And the last solution which i found was creating an httpmodule to intercept the web request.

using System;

using System.Collections.Generic;

using System.Text;

using System.Web;

namespace HAMModule{

public class MyModule : IHttpModule{

public void Init(HttpApplication app){

app.BeginRequest += new EventHandler(app_BeginRequest);

}

void app_BeginRequest(object sender, EventArgs e){

HttpContext context = ((HttpApplication)sender).Context;

// check for size if more than 4 mb

if (context.Request.ContentLength > 4096000){

IServiceProvider provider = (IServiceProvider)context;

HttpWorkerRequest wr = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));

// Check if body contains data

if (wr.HasEntityBody()){

// get the total body length

int requestLength = wr.GetTotalEntityBodyLength();

// Get the initial bytes loaded

int initialBytes = wr.GetPreloadedEntityBody().Length;

if (!wr.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 = wr.ReadEntityBody(buffer, buffer.Length);

// Update the received bytes

receivedBytes += initialBytes;

}

initialBytes = wr.ReadEntityBody(buffer, requestLength – receivedBytes);}}

// Redirect the user to an error page.

context.Response.Redirect(“Error.aspx”);}}

public void Dispose(){}

}}

and add the following information to web.config

<httpModules>

<add type=HAMModule.MyModule name=MyModule/>

</httpModules>

inside

<system.web>

The last solution worked properly!!!!

BeginRequest event –The BeginRequest event signals the creation of any given new request. This event is always raised and is always the first event to occur during the processing of a request.

Article on creating a custom http module

http://msdn.microsoft.com/en-us/library/ms227673(VS.80).aspx


Bye..

Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

8 thoughts on “FileUpload : Page Cannot be displayed and maximum request length exceeded error”

  1. I tried these steps and am still getting “Page cannot be displayed” error. Basically I want to stop the upload if the content length is above a certain value. Doing any kind of response.end, etc. causes “Page cannot be displayed”. Is there a way to show a friendly error about this to the user?

    I would appreciate any tips on this.

    Thanks!

    Like

  2. Quoted from Chris Hynes (http://stackoverflow.com/questions/674651/uploading-files-past-asp-net-request-length-limit)

    “Because of the nature of HTTP, you can’t actually return anything until you read all the request data. When you receive an oversized request, you have two options:

    Read in all the data and then return a nice error page. This sounds good, but means the user has to wait for the upload to complete before he gets the message that he can’t upload. It also opens a possible DOS attack hole.

    Terminate the request immediately. This gives the user a crappy disconnect page, but preserves security.

    There is a third option — use an advanced component that provides both nice error messages as well as security. You can use flash only components, and there are many of them out there, but of course, if the user doesn’t have flash, you’re out of luck.”

    Like

  3. Well, code is nice. Have seen it on different places on the web.
    But it’s still not working for me. Can’t get it to work.
    Got the same error as coder3000: “Page cannot be displayed”

    Like

  4. Awesome, fixed my problem by just adding this web.config

    and these lines to upload event
    if (fulAttachFile.PostedFile.ContentLength >= 4194304)
    {
    cstnVldErrorMaxFileSize.IsValid = false;
    return;
    }

    Thanks a lot

    Like

Please share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

CRM for You and Me

Customer Relationship Mgt App for the Professional

D CRM Explorer

Learn about Microsoft Dynamics CRM Power Platform customization and implementation and other cool stuffs

Stroke // Jonas Rapp

I know pre-stroke. I will improve who I was.

Power Melange

Power Melange By Shalinee

Clavin's Blog

Power Automate - Power Apps - SharePoint Online - Azure - Nintex - K2 - Artificial Intelligence

Sat Sangha Salon

An Inquiry in Being

The Indoencers

The Influencers & Influences of Indian Music

Monika Halan's blog

Hand's-free money management

D365 Demystified

A closer look at Microsoft Dynamics 365.

Microsoft Mate (msftmate) - Andrew Rogers

Experienced consultant primarily focused on Microsoft Dynamics 365 and the Power Platform

Knowhere365

Specific topics by Django Lohn on the whole Microsoft365 Stack

Manmit Rahevar's Blog

One Stop Destination for Microsoft Technology Solutions

MG

Naturally Curious

Brian Illand

Power Platform and Dynamics 365

Steve Mordue MVP

A Microsoft Business Applications MVP

Subwoofer 101

Bass defines your home theater

SQLTwins by Nakul Vachhrajani

SQL Server tips and experiences dedicated to my twin daughters.

Everything D365

Discovering Azure DevOps and D365 Business Applications

Tech Wizard

Lets do IT Spells

Two Bite Tips

Valuable Tips To Grow Your Business

XRM Tricks (Power Platform & Dynamics CRM )

Power Platform & Dynamics CRM

CRM TIPS BY PRM

Mail to crmtipsbyprm@gmail.com for queries and suggestions

nijos.dev

Giving back to the community what I have learned

xrm CRM Dynamics

Dynamics CRM Technical & Functional Info

Dynamics 365 Blogs - Explained in unique way

Sometimes you need to look at things from different perspective.

CRM Keeper

Dynamics 365 Customer Engagement, CRM, Microsoft CRM, Dynamics CRM

EVOLVED365

Step into the world of a Dynamics 365 Consultant

Dianamics PCF Lady

Diana & Dynamics 365 & Power Platform

Sara Lagerquist

No Code Customization Concepts

innovativeaj

developer, designer, writer, fun loving, patriotic, humble and a sweet person inside out :) love and respect people who have a great sense of humor.

Temmy Wahyu Raharjo

Dreaming to be a clean coder and TDD minded programmer.

Transform 365

We blog about problems we face and code we write to help others

%d bloggers like this: