【发布时间】:2013-09-12 20:01:18
【问题描述】:
我正在尝试限制用户可以在特定页面上上传的文件大小。我已经使用web.config 做到了这一点,如下所示:
<location path="SubSection/TestPage">
<system.web>
<httpRuntime maxRequestLength="2048" />
</system.web>
</location>
但是,当出现此错误时,它会将用户带到那些 ASP.NET 黄色错误页面之一。现在我知道可以创建自定义错误页面,并且我已经对此进行了研究,但它们仍然涉及重定向浏览器。
这只是为了尝试通知用户他们正在尝试上传一个太大的文件,而不是让他们离开他们当前所在的页面。是否可以阻止此 TestPage 重定向到黄色错误页面,而是显示某种 JavaScript 弹出窗口?
我尝试处理global.asax 文件中Application_Error() 方法中的错误,但不幸的是,无论我在其中做什么,它似乎总是在此方法完成后重定向。我试图通过这个页面显示一个 JavaScript 弹出窗口的尝试也没有成功,虽然我的理解是这实际上在 global.asax 文件中是可能的,所以我认为我只是在那里做错了什么。
这是我处理Application_Error() 的代码,基于here 接受的答案,JavaScript 部分基于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();
}
}
}
最后,根据this 接受的答案,我还在用户控件本身(位于VB.NET)中尝试了以下代码:
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
不幸的是,这段代码似乎根本没有被调用。
重申一下,这只是为了处理一个简单的用户错误,例如上传一个稍微过大的文件。我不想重定向并丢失用户可能在原始页面上所做的其他事情,我只想显示一个简单的 JavaScript 警报框。这个可以吗?
【问题讨论】:
-
您只需要检查文件大小..如果超过该大小,那么您应该显示非常简单的警报消息..
标签: c# asp.net vb.net global-asax javascript