"최대 요청 길이를 초과했습니다"잡기
업로드 기능을 작성 httpRuntime
중이며 web.config 에서 지정된 최대 크기 (최대 크기는 5120으로 설정 됨) 보다 큰 파일에서 "System.Web.HttpException : 최대 요청 길이를 초과했습니다"를 발견하는 데 문제가 있습니다 . <input>
파일에 간단한 것을 사용 하고 있습니다.
문제는 업로드 버튼의 클릭 이벤트 전에 예외가 발생하고 코드가 실행되기 전에 예외가 발생한다는 것입니다. 그렇다면 예외를 어떻게 포착하고 처리합니까?
편집 : 예외가 즉시 발생하므로 느린 연결로 인해 시간 초과 문제가 아니라고 확신합니다.
불행히도 그러한 예외를 잡는 쉬운 방법은 없습니다. 내가하는 일은 페이지 수준의 OnError 메서드 또는 global.asax의 Application_Error를 재정의 한 다음 Max Request 실패인지 확인한 다음 오류 페이지로 전송하는 것입니다.
protected override void OnError(EventArgs e) .....
private void Application_Error(object sender, EventArgs e)
{
if (GlobalHelper.IsMaxRequestExceededException(this.Server.GetLastError()))
{
this.Server.ClearError();
this.Server.Transfer("~/error/UploadTooLarge.aspx");
}
}
그것은 해킹이지만 아래 코드는 나를 위해 작동합니다.
const int TimedOutExceptionCode = -2147467259;
public static bool IsMaxRequestExceededException(Exception e)
{
// unhandled errors = caught at global.ascx level
// http exception = caught at page level
Exception main;
var unhandled = e as HttpUnhandledException;
if (unhandled != null && unhandled.ErrorCode == TimedOutExceptionCode)
{
main = unhandled.InnerException;
}
else
{
main = e;
}
var http = main as HttpException;
if (http != null && http.ErrorCode == TimedOutExceptionCode)
{
// hack: no real method of identifying if the error is max request exceeded as
// it is treated as a timeout exception
if (http.StackTrace.Contains("GetEntireRawContent"))
{
// MAX REQUEST HAS BEEN EXCEEDED
return true;
}
}
return false;
}
GateKiller는 maxRequestLength를 변경해야한다고 말했습니다. 업로드 속도가 너무 느린 경우 executionTimeout을 변경해야 할 수도 있습니다. 이 설정 중 어느 것도 너무 커지는 것을 원하지 않으면 DOS 공격에 노출 될 수 있습니다.
executionTimeout의 기본값은 360 초 또는 6 분입니다.
httpRuntime 요소를 사용하여 maxRequestLength 및 executionTimeout을 변경할 수 있습니다 .
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<httpRuntime maxRequestLength="102400" executionTimeout="1200" />
</system.web>
</configuration>
편집하다:
If you want to handle the exception regardless then as has been stated already you'll need to handle it in Global.asax. Here's a link to a code example.
You can solve this by increasing the maximum request length in your web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<httpRuntime maxRequestLength="102400" />
</system.web>
</configuration>
The example above is for a 100Mb limit.
Hi solution mentioned by Damien McGivern, Works on IIS6 only,
It does not work on IIS7 and ASP.NET Development Server. I get page displaying "404 - File or directory not found."
Any ideas?
EDIT:
Got it... This solution still doesn't work on ASP.NET Development Server, but I got the reason why it was not working on IIS7 in my case.
The reason is IIS7 has a built-in request scanning which imposes an upload file cap which defaults to 30000000 bytes (which is slightly less that 30MB).
And I was trying to upload file of size 100 MB to test the solution mentioned by Damien McGivern (with maxRequestLength="10240" i.e. 10MB in web.config). Now, If I upload the file of size > 10MB and < 30 MB then the page is redirected to the specified error page. But if the file size is > 30MB then it show the ugly built-in error page displaying "404 - File or directory not found."
So, to avoid this, you have to increase the max. allowed request content length for your website in IIS7. That can be done using following command,
appcmd set config "SiteName" -section:requestFiltering -requestLimits.maxAllowedContentLength:209715200 -commitpath:apphost
I have set the max. content length to 200MB.
After doing this setting, the page is succssfully redirected to my error page when I try to upload file of 100MB
Refer, http://weblogs.asp.net/jgalloway/archive/2008/01/08/large-file-uploads-in-asp-net.aspx for more details.
If you are wanting a client side validation also so you get less of a need to throw exceptions you could try to implement client side file size validation.
Note: This only works in browsers that support HTML5. http://www.html5rocks.com/en/tutorials/file/dndfiles/
<form id="FormID" action="post" name="FormID">
<input id="target" name="target" class="target" type="file" />
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$('.target').change(function () {
if (typeof FileReader !== "undefined") {
var size = document.getElementById('target').files[0].size;
// check file size
if (size > 100000) {
$(this).val("");
}
}
});
</script>
Here's an alternative way, that does not involve any "hacks", but requires ASP.NET 4.0 or later:
//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(httpException.WebEventCode == WebEventCodes.RuntimeErrorPostTooLarge)
{
//handle the error
Response.Write("Sorry, file is too big"); //show this message for instance
}
}
One way to do this is to set the maximum size in web.config as has already been stated above e.g.
<system.web>
<httpRuntime maxRequestLength="102400" />
</system.web>
then when you handle the upload event, check the size and if its over a specific amount, you can trap it e.g.
protected void btnUploadImage_OnClick(object sender, EventArgs e)
{
if (fil.FileBytes.Length > 51200)
{
TextBoxMsg.Text = "file size must be less than 50KB";
}
}
A solution that works with IIS7 and upwards: Display custom error page when file upload exceeds allowed size in ASP.NET MVC
In IIS 7 and beyond:
web.config file:
<system.webServer>
<security >
<requestFiltering>
<requestLimits maxAllowedContentLength="[Size In Bytes]" />
</requestFiltering>
</security>
</system.webServer>
You can then check in code behind, like so:
If FileUpload1.PostedFile.ContentLength > 2097152 Then ' (2097152 = 2 Mb)
' Exceeded the 2 Mb limit
' Do something
End If
Just make sure the [Size In Bytes] in the web.config is greater than the size of the file you wish to upload then you won't get the 404 error. You can then check the file size in code behind using the ContentLength which would be much better
As you probably know, the maximum request length is configured in TWO places.
maxRequestLength
- controlled at the ASP.NET app levelmaxAllowedContentLength
- under<system.webServer>
, controlled at the IIS level
The first case is covered by other answers to this question.
To catch THE SECOND ONE you need to do this in global.asax:
protected void Application_EndRequest(object sender, EventArgs e)
{
//check for the "file is too big" exception if thrown at the IIS level
if (Response.StatusCode == 404 && Response.SubStatusCode == 13)
{
Response.Write("Too big a file"); //just an example
Response.End();
}
}
After tag
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="4500000" />
</requestFiltering>
</security>
add the following tag
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" subStatusCode="13" />
<error statusCode="404" subStatusCode="13" prefixLanguageFilePath="" path="http://localhost/ErrorPage.aspx" responseMode="Redirect" />
</httpErrors>
you can add the Url to the error page...
You can solve this by increasing the maximum request length and execution time out in your web.config:
-Please Clarify the maximum execution time out grater then 1200
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <httpRuntime maxRequestLength="102400" executionTimeout="1200" /> </system.web> </configuration>
How about catch it at EndRequest event?
protected void Application_EndRequest(object sender, EventArgs e)
{
HttpRequest request = HttpContext.Current.Request;
HttpResponse response = HttpContext.Current.Response;
if ((request.HttpMethod == "POST") &&
(response.StatusCode == 404 && response.SubStatusCode == 13))
{
// Clear the response header but do not clear errors and
// transfer back to requesting page to handle error
response.ClearHeaders();
HttpContext.Current.Server.Transfer(request.AppRelativeCurrentExecutionFilePath);
}
}
It can be checked via:
var httpException = ex as HttpException;
if (httpException != null)
{
if (httpException.WebEventCode == System.Web.Management.WebEventCodes.RuntimeErrorPostTooLarge)
{
// Request too large
return;
}
}
참고URL : https://stackoverflow.com/questions/665453/catching-maximum-request-length-exceeded
'IT story' 카테고리의 다른 글
파이썬에서 dict 객체의 연합 (0) | 2020.08.03 |
---|---|
Google Cloud Bigtable 및 Google Cloud Datastore (0) | 2020.08.03 |
C # 사전은 어떻게됩니까? (0) | 2020.08.03 |
VIM에서 REPLACE 모드로 전환하는 방법 (0) | 2020.08.03 |
Amazon S3 Boto-폴더 생성 방법 (0) | 2020.08.03 |