I'm trying to restrict how large a file a user can upload on a particular page. I've done this using web.config
like this:
<location path="SubSection/TestPage">
<system.web>
<httpRuntime maxRequestLength="2048" />
</system.web>
</location>
However, when this errors, it takes the user to one of those ASP.NET yellow-error pages. Now I know it is possible to create custom error pages, and I've looked into this, but they still involve redirecting the browser.
This is simply for trying inform the user that they are trying to upload a file that is too large, without navigating them away from the page they are currently on. Is it possible to prevent this TestPage from redirecting to the yellow-error page, and instead display a JavaScript popup of some kind?
I have tried to handle the error in the Application_Error()
method in the global.asax
file, but unfortunately it always seems to redirect after this method finishes, regardless of what I do in it. My attempts to display a JavaScript popup through this page were also not successful, although my understanding is that this is actually possible in the global.asax
file, so I would assume I'm simply doing something wrong there.
This is my code for handling Application_Error()
, based on the accepted answer from here, with the JavaScript part based on this.
void Application_Error(object sender, EventArgs e)
{
int TimedOutExceptionCode = -2147467259;
Exception mainEx;
Exception lastEx = Server.GetLastError();
HttpUnhandledException unhandledEx = lastEx as HttpUnhandledException;
if (unhandledEx != null && unhandledEx.ErrorCode == TimedOutExceptionCode)
{
mainEx = unhandledEx.InnerException;
}
else
mainEx = lastEx;
HttpException httpEx = mainEx as HttpException;
if (httpEx != null && httpEx.ErrorCode == TimedOutExceptionCode)
{
if(httpEx.StackTrace.Contains("GetEntireRawContent"))
{
System.Web.UI.Page myPage = (System.Web.UI.Page)HttpContext.Current.Handler;
myPage.RegisterStartupScript("alert","<script language=javascript>alert('The file you attempted to upload was too large. Please try another.');</script" + ">");
Server.ClearError();
}
}
}
Finally, I have also tried the following code in the user control itself (which is in VB.NET
), based on the accepted answer from this:
Private Sub Page_Error(ByVal sender As Object, ByVal e As EventArgs)
Dim err As Exception = Server.GetLastError()
Dim cs As ClientScriptManager = Page.ClientScript
If (cs.IsStartupScriptRegistered(Me.GetType(), "testJS") = False)
Dim cstext1 As String = "alert('" & err.Message & "');"
cs.RegisterStartupScript(Me.GetType(), "testJS", cstext1, True)
End If
End Sub
Unfortunately, this code did not seem to get called at all.
To reiterate, this is just for handling, say, a simple user mistake in uploading a file that is slightly too large. I don't want to redirect and lose what else the user may have done on the original page, I just want to display a simple JavaScript alert box. Can this be done?