Uploading large files in ASP.NET applications can trigger the Maximum Request Length Exceeded error. This is often encountered when users attempt to upload large videos or documents. The error occurs because ASP.NET restricts the size of the request content to prevent potential abuse and excessive memory consumption.
Thankfully, you can solve this with a few updates to your web.config
file and optionally by handling the error gracefully in your code.
⚙️ Adjusting Limits in web.config
To increase the allowed upload size, you need to update two different configuration settings in your web.config
file:
<configuration>
<system.web>
<httpRuntime maxRequestLength="1048576" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
</system.webServer>
</configuration>
What These Values Mean
maxRequestLength
is measured in kilobytesmaxAllowedContentLength
is measured in bytes
In the example above:
maxRequestLength="1048576"
allows up to 1 GB (1,048,576 KB)maxAllowedContentLength="1073741824"
allows up to 1 GB (1,073,741,824 bytes)
Both values must be set accordingly to prevent size mismatch errors.
🔐 Why There Are Two Different Settings
ASP.NET and IIS use separate mechanisms to validate request sizes. The <httpRuntime>
setting is handled by the ASP.NET pipeline while <requestLimits>
is enforced by IIS at a lower level. Failing to adjust both settings often results in the same error persisting even after changing one of them.
📢 Giving Meaningful Feedback to Users
If a user uploads a file that exceeds the configured limits, your application can respond more gracefully by catching the error and showing a helpful message instead of a generic error page.
You can handle this using the Application_Error
method in Global.asax
:
// 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 (((System.Web.HttpException)httpException.InnerException).WebEventCode
== System.Web.Management.WebEventCodes.RuntimeErrorPostTooLarge)
{
// Inform the user clearly
Response.Write("The uploaded file is too large. Please upload a smaller file.");
Server.ClearError();
}
}
This way your users are not left guessing why their upload failed.
✅ Summary
Increase upload limits using
maxRequestLength
andmaxAllowedContentLength
Ensure values match across units (KB vs bytes)
Handle oversized uploads gracefully with custom error handling
Configuring upload size correctly and handling exceptions clearly ensures your users have a smooth experience without mysterious server errors.