如果使用asp.net上传文件超过服务器端的最大限制,如何向用户发送消息。 我在global.asax
中使用了以下代码Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
Dim ex As New Exception
ex = Server.GetLastError()
If TypeOf ex Is HttpUnhandledException AndAlso ex.InnerException IsNot Nothing Then
ex = ex.InnerException
End If
If (ex IsNot Nothing) And ex.Message.Contains("Maximum request length exceeded") Then
Server.ClearError()
Server.Transfer("/Errors.aspx")
End If
End Sub
它不显示错误页面而是让Internet Explorer无法显示网页
答案 0 :(得分:0)
这在周期中已经太晚了。在Application_BeginRequest中测试它,如下所示:
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim runtime As HttpRuntimeSection = CType(WebConfigurationManager.GetSection("system.web/httpRuntime"), HttpRuntimeSection)
' Approx 100 Kb(for page content) size has been deducted because the maxRequestLength proprty
' is the page size, not only the file upload size
Dim maxRequestLength As Integer = (runtime.MaxRequestLength - 100) * 1024
' This code is used to check the request length of the page and if the request length is
' greater than MaxRequestLength then return to the same page with extra query string value action=exception
Dim myContext As HttpContext = CType(sender, HttpApplication).Context
If myContext.Request.ContentLength > maxRequestLength Then
' We need to consume the file otherwise the browser will detect that the upload did not complete
' and assume that the connection was broken and display a "page not found" error
Dim pro As IServiceProvider = CType(myContext, IServiceProvider)
Dim workerRequest As HttpWorkerRequest = DirectCast(pro.GetService(GetType(HttpWorkerRequest)), HttpWorkerRequest)
If workerRequest.HasEntityBody Then
Dim requestLength As Integer = workerRequest.GetTotalEntityBodyLength
Dim initialBytes As Integer = 0
If workerRequest.GetPreloadedEntityBody IsNot Nothing Then
initialBytes = workerRequest.GetPreloadedEntityBody.Length
End If
If Not workerRequest.IsEntireEntityBodyIsPreloaded Then
Dim buffer As Byte() = New Byte(511999) {}
Dim receivedBytes As Integer = initialBytes
While (requestLength - receivedBytes) >= initialBytes
initialBytes = workerRequest.ReadEntityBody(buffer, buffer.Length)
receivedBytes += initialBytes
End While
initialBytes = workerRequest.ReadEntityBody(buffer, requestLength - receivedBytes)
End If
Response.Redirect("~/Utility/ErrorMaxLength.htm")
End If
End If
End Sub
来源http://weblogs.asp.net/hosamkamel/resolving-maximum-request-length-exceeded-exception