I am getting the error Maximum request length exceeded when I am trying to upload a video in my site.
How do I fix this?
Neeraj Kumar
7712 gold badges16 silver badges37 bronze badges
asked Oct 4, 2010 at 8:48
Surya sasidharSurya sasidhar
29.7k57 gold badges139 silver badges220 bronze badges
0
If you are using IIS for hosting your application, then the default upload file size is 4MB. To increase it, please use this below section in your web.config
—
<configuration>
<system.web>
<httpRuntime maxRequestLength="1048576" />
</system.web>
</configuration>
For IIS7 and above, you also need to add the lines below:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
</system.webServer>
Note:
maxRequestLength
is measured in kilobytesmaxAllowedContentLength
is measured in bytes
which is why the values differ in this config example. (Both are equivalent to 1 GB.)
SharpC
6,9944 gold badges45 silver badges40 bronze badges
answered Oct 4, 2010 at 8:52
Sachin ShanbhagSachin Shanbhag
54.6k11 gold badges89 silver badges103 bronze badges
18
I don’t think it’s been mentioned here, but to get this working, I had to supply both of these values in the web.config:
In system.web
<httpRuntime maxRequestLength="1048576" executionTimeout="3600" />
And in system.webServer
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
IMPORTANT : Both of these values must match. In this case, my max upload is 1024 megabytes.
maxRequestLength has 1048576 KILOBYTES, and maxAllowedContentLength has 1073741824 BYTES.
I know it’s obvious, but it’s easy to overlook.
answered Sep 19, 2012 at 13:45
14
It may be worth noting that you may want to limit this change to the URL you expect to be used for the upload rather then your entire site.
<location path="Documents/Upload">
<system.web>
<!-- 50MB in kilobytes, default is 4096 or 4MB-->
<httpRuntime maxRequestLength="51200" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<!-- 50MB in bytes, default is 30000000 or approx. 28.6102 Mb-->
<requestLimits maxAllowedContentLength="52428800" />
</requestFiltering>
</security>
</system.webServer>
</location>
answered May 6, 2013 at 16:57
Nick AlbrechtNick Albrecht
16.6k10 gold badges66 silver badges101 bronze badges
10
And just in case someone’s looking for a way to handle this exception and show a meaningful explanation to the user (something like «You’re uploading a file that is too big»):
//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)
{
//handle the error
Response.Write("Too big a file, dude"); //for example
}
}
(ASP.NET 4 or later required)
answered May 23, 2015 at 19:58
Serge ShultzSerge Shultz
5,8983 gold badges27 silver badges17 bronze badges
4
The maximum request size is, by default, 4MB (4096 KB)
This is explained here.
The above article also explains how to fix this issue
answered Oct 4, 2010 at 8:51
DaveDave
6,9152 gold badges32 silver badges35 bronze badges
2
If you can’t update configuration files but control the code that handles file uploads use HttpContext.Current.Request.GetBufferlessInputStream(true)
.
The true
value for disableMaxRequestLength
parameter tells the framework to ignore configured request limits.
For detailed description visit https://msdn.microsoft.com/en-us/library/hh195568(v=vs.110).aspx
answered Aug 10, 2017 at 7:13
3
There’s an element in web.config to configure the max size of the uploaded file:
<httpRuntime
maxRequestLength="1048576"
/>
bkaid
51.5k22 gold badges112 silver badges128 bronze badges
answered Oct 4, 2010 at 8:52
emaema
5,6881 gold badge26 silver badges31 bronze badges
To summarize all the answers in a single place:
<system.web>
<httpRuntime targetFramework="4.5.2" maxRequestLength="1048576"/>
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
</system.webServer>
Rules:
- maxRequestLength (expressed in kb) value must match
maxAllowedContentLength (expressed in bytes). - most of the time your system.web section may already contains an «httpRuntime». set your targetFramework to the version of your .net used.
Notes:
- default value for maxRequestLength is 4096 (4mb). max value is 2,147,483,647
- default value for maxAllowedContentLength is 30,000,000 (around 30mb). max value is 4,294,967,295
more info MSDN
answered Mar 21, 2018 at 17:46
BernieSFBernieSF
1,7321 gold badge28 silver badges42 bronze badges
2
maxRequestLength (length in KB) Here as ex. I took 1024 (1MB) maxAllowedContentLength (length in Bytes) should be same as your maxRequestLength (1048576 bytes = 1MB).
<system.web>
<httpRuntime maxRequestLength="1024" executionTimeout="3600" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1048576"/>
</requestFiltering>
</security>
</system.webServer>
CountZero
6,2013 gold badges46 silver badges59 bronze badges
answered Dec 4, 2015 at 9:07
UniCoderUniCoder
3,02527 silver badges26 bronze badges
It bothered me for days too.
I modified the Web.config file but it didn’t work.
It turned out that there are two Web.config file in my project,
and I should modified the one in the ROOT directory, not the others.
Hope this would be helpful.
answered Dec 31, 2015 at 3:13
NiaoBlushNiaoBlush
611 silver badge1 bronze badge
0
If you have a request going to an application in the site, make sure you set maxRequestLength in the root web.config. The maxRequestLength in the applications’s web.config appears to be ignored.
answered Oct 19, 2015 at 23:15
mhenry1384mhenry1384
7,5585 gold badges55 silver badges74 bronze badges
1
I was tripped up by the fact that our web.config file has multiple system.web sections: it worked when I added < httpRuntime maxRequestLength=»1048576″ /> to the system.web section that at the configuration level.
answered Apr 18, 2016 at 14:52
Graham LaightGraham Laight
4,7003 gold badges30 silver badges28 bronze badges
I had to edit the C:\Windows\System32\inetsrv\config\applicationHost.config
file and add <requestLimits maxAllowedContentLength="1073741824" />
to the end of the…
<configuration>
<system.webServer>
<security>
<requestFiltering>
section.
As per This Microsoft Support Article
answered Jan 30, 2017 at 0:48
HyperActiveHyperActive
1,13912 silver badges12 bronze badges
1
I was dealing with same error and after spending time solved it by adding below lines in web.config file
<system.web>
<httpRuntime targetFramework="4.7.1" maxRequestLength="1048576"/>
</system.web>
and
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
</system.webServer>
answered Nov 23, 2020 at 17:16
Nida AkramNida Akram
3422 gold badges9 silver badges25 bronze badges
Caution: As some have pointed out, there was already an entry for <httpRuntime.. in my web.config file. I had blindly copied and pasted another httpRuntime from here and it crashed the whole site.
answered Mar 11 at 7:54
I can add to config web uncompiled
<system.web>
<httpRuntime maxRequestLength="1024" executionTimeout="3600" />
<compilation debug="true"/>
</system.web>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1048576"/>
</requestFiltering>
</security>
Paul Roub
36.3k27 gold badges84 silver badges93 bronze badges
answered Jan 20, 2016 at 13:52
1
Время на прочтение
3 мин
Количество просмотров 20K
На написание данной статьи-заметки меня сподвигла работа над формой обратной связи, в которой имелась возможность отправки файлов на сервер. Естественным образом, захотелось ограничить размер загружаемых файлов со стороны сервера и выдавать пользователю соответствующее сообщение. Хорошая новость заключалась в том, что ASP.NET имеет встроенные средства для такого ограничения. Плохая – нет лёгких путей обработки данной ситуации.
Суть проблемы
В ASP.NET можно задать ограничение на размер запроса в web.config:
<system.web>
<httpRuntime maxRequestLength="1000"/>
Значение задаётся в килобайтах, по умолчанию – 4096 КБ. Очевидно, что для каждого location можно задавать свои ограничения.
Замечание: В IIS 7+ дополнительно существует своя возможность фильтрации запросов:
<system.webServer>
<security>
<requestFiltering>
<!--ограничение на размер запроса в байтах-->
<requestLimits maxAllowedContentLength="30000000"></requestLimits>
Т.ч. менять эти два параметра нужно в паре.
Стандартного способа перехвата и обработки исключения о превышении данного ограничения в ASP.NET нет. Первое, что приходит в голову – это ловить исключение в Global.asax обработчиком события Error. Но это оказалось не кошерным по 2-м причинам:
- Специального типа исключения нет, а выбрасывается общий System.Web.HttpException (обёрнутое, разумеется, в HttpUnhandledException) с сообщением «Maximum request length exceeded.» в английской локали. Т.ч. гарантированного способа получить нашего «клиента» не имеем.
- Опытным путём столкнулся с тем, что к моменту перехвата исключения сервер уже успевает отослать клиенту часть ответа, поэтому осложняется пользование объектом Response.
Решение
Решение подглядел тут. Но сдаётся мне, что товарищ несколько перемудрил. У меня получилось проще и, на мой взгляд, точнее. В Global.asax в самом начале обработки запроса проверяем его размер и редиректим пользователя, если что, на специально подготовленную страничку:
public override void Init()
{
base.Init();
this.BeginRequest += GlobalBeginRequest;
}
private void GlobalBeginRequest(object sender, EventArgs e)
{
var runTime = (HttpRuntimeSection)WebConfigurationManager.GetSection("system.web/httpRuntime");
var maxRequestLength = runTime.MaxRequestLength * 1024;
if (Request.ContentLength > maxRequestLength)
{
// или другой свой код обработки
Response.Redirect("~/filetoolarge/");
}
}
Пара пояснений.
Первое по поводу
var runTime = (HttpRuntimeSection)WebConfigurationManager.GetSection("system.web/httpRuntime");
Первая мысль была запомнить этот параметр в отдельное свойство приложения на стадии его старта. Но это не есть правильно, т.к. у разных директорий на сайте могут быть свои параметры.
Второе про
var maxRequestLength = runTime.MaxRequestLength * 1024;
Я так и не понял, зачем первоисточник пытался вычесть 100 КБ. Ограничение ASP.NET работает на весь запрос в совокупности (тестировалось на ASP.NET 2, .NET 3.5, IIS 6) вместе с данными формы и всеми прикрепленными файлами.
Ну, вот и всё, что я хотел рассказать по этому поводу. Хотя нет. Наверное, нужно добавить, что по-хорошему нужна клиентская валидация, в т.ч. и на размер файла. Для этого нужно использовать сторонние компоненты, т.к. встроенные браузерные контролы загрузки файлов – это отдельный порядочный головняк. Возможно, отдельные реализации умеют решать затронутую проблему комплексно.
Table of Contents
- Introduction
- Scenario
- Cause
- Solution
- Set the Maximum Request Length in Report Server Web Config
- Set the Maximum Request Length in Report Manager Web Config
- Uploading large report in SQL Server Reporting Service.
- Applies To
- Conclusion
- Reference
Introduction
In this article, we will overcome the «Maximum request length exceeded» issue that occurs when upload large size report in SQL Server Reporting Service.
Scenario
In SQL Server Reporting Service 2012,
we tried to upload a new report that its size ~6 MB via Report Manager, unfortunately, we got the below error
SQL Server Reporting Services Error: Maximum request length exceeded.
Cause
By default, the Maximum Request Length is
4 MB, so that this issue occurs in case the uploaded report size is larger than 4 MB.
Solution
In SQL Server Reporting Service, to adjust the
Maximum Request Length default value, you should edit the «httpruntime» tag setting in
- Report Server Web Config.
- Report Manager Web Config
Set the Maximum Request Length in Report Server Web Config
- Go to «C:\Program Files\Microsoft SQL Server\MSRS11.SQLInstance\Reporting Services«.
- Note: The MSRS11.SQLInstance depends on your SQL Instance Name.
- Open the «Report Server» Folder > Edit the Web.config with an appropriate editor.
- Search for «httpRuntime» tag > add Add «maxRequestLength» propery > set it to appropriate
limit (KB) based on the maximum report size you have.- In our case, the report size is larger than 6MB, so we should set it as maxRequestLength=»70000″
- In our case, the report size is larger than 6MB, so we should set it as maxRequestLength=»70000″
- Save and Close.
Set the Maximum Request Length in Report Manager Web Config
- Again, Go to «C:\Program Files\Microsoft SQL Server\MSRS11.SQLInstance\Reporting Services«.
- Note: The MSRS11.SQLInstance depends on your SQL Instance Name.
- Open the «Report Manager» Folder > Edit the Web.config with an appropriate editor.
- Search for «httpRuntime» tag > add Add «maxRequestLength» propery > set it to appropriate
limit (KB) based on the maximum report size you have.- In our case, the report size is larger than 6MB, so we should set it as maxRequestLength=»70000″
- In our case, the report size is larger than 6MB, so we should set it as maxRequestLength=»70000″
- Save and Close.
Uploading large report in SQL Server Reporting Service.
After you have set the Maximum Request Length in Report Manager and Report Server web configs, try now to upload the report via Report Manager that should be uploaded properly as explained below:
Applies To
- SQL Server 2014.
- SQL Server 2012.
- SQL Server 2008.
Conclusion
Large file uploads in ASP.NET
Uploading files via the FileUpload
control gets tricky with big files. The default maximum filesize is 4MB
— this is done to prevent denial of service attacks in which an
attacker submitted one or more huge files which overwhelmed server
resources. If a user uploads a file larger than 4MB, they’ll get an
error message: «Maximum request length exceeded.»
Server Error in '/' Application.
------------------------------
Maximum request length exceeded.
Solution:
The 4MB default is set in machine.config, but you can override it in you
web.config. For instance, to expand the upload limit to 20MB, add below code to web.config:
<
system.web
>
<
httpRuntime
executionTimeout
=
"240"
maxRequestLength
=
"20480"
/>
</
system.web
>
IIS7(and later version) has a built-in request scanning which imposes an upload file cap which defaults to 30MB. To increase it, you also need to add the lines below:
<
system.webServer
>
<
security
>
<
requestFiltering
>
<
requestLimits
maxAllowedContentLength
=
"3000000000"
/>
</
requestFiltering
>
</
security
>
</
system.webServer
>
Note: maxAllowedContentLength is measured in bytes while maxRequestLength is measured in kilobytes.
Warning: If you are using our shared hosting plan, we do not recommend you to upload large files via script which will slow down your site loading speed. You can upload it via FTP instead.
Article ID: 1544, Created: January 6, 2014 at 11:09 PM, Modified: January 6, 2014 at 11:51 PM
In this post, we want to discuss an error “maximum request length exceeded” of FileUploader control in ASP.Net. Before we get started, if you want to know about the uses of a function key, please go through the following article: The best use of Function Keys (F1 to F12).
Introduction
ASP.NET FileUpload control allows us to upload files to a Web Server or storage in a Web Form. The control is a part of ASP.NET controls and can be placed on a Web Form by simply dragging and dropping from Toolbox to a WebForm. The FileUpload control was introduced in ASP.NET 2.0.
With ASP.NET, accepting file uploads from users has become extremely easy. With the FileUpload control, it can be done with a small number of code lines, as you will see in the following example.
How to upload a file using the FileUploader control
<form id=«form1» runat=«server»> <asp:FileUpload id=«FileUploadControl» runat=«server» /> <asp:Button runat=«server» id=«UploadButton» text=«Upload» onclick=«UploadButton_Click» /> <br /><br /> <asp:Label runat=«server» id=«StatusLabel» text=«Upload status: « /> </form> |
And here is the code-behind code required to handle the upload:
Code-behind code of FileUploader control
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
protected void UploadButton_Click(object sender, EventArgs e) { if(FileUploadControl.HasFile) { try { string filename = Path.GetFileName(FileUploadControl.FileName); FileUploadControl.SaveAs(Server.MapPath(«~/») + filename); StatusLabel.Text = «Upload status: File uploaded!»; } catch(Exception ex) { StatusLabel.Text = «Upload status: The file could not be uploaded. The following error occured: « + ex.Message; } } } |
Maximum request length exceeded Problem
Uploading files via the FileUpload control gets tricky with big files. The default maximum file size is 4MB – this is done to prevent denial of service attacks in which an attacker submitted one or more huge files which overwhelmed server resources. If a user uploads a file larger than 4MB, they’ll get an error message: “Maximum request length exceeded.”
Efficient solution for the problem
The 4MB default is set in the machine.config, but you can override it in your web.config. For instance, to expand the upload limit to 20MB, add the below code to the web. config:
<system.web> <httpRuntime executionTimeout=«240» maxRequestLength=«20480» /> </system.web> |
IIS7 (and later version) has a built-in request scanning which imposes an upload file cap that defaults to 30MB. To increase it, you also need to add the lines below:
<system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength=«3000000000» /> </requestFiltering> </security> </system.webServer> |
Note: maxAllowedContentLength is measured in bytes while maxRequestLength is measured in kilobytes.
The article was published on March 1, 2020 @ 12:12 PM