У меня была похожая проблема несколько месяцев назад, этот пост был чрезвычайно полезен: http://www.velocityreviews.com/forums/showpost.php?p=3794467&postcount=8
По сути, вы добавляете код в код global.asax, чтобы прослушивать каждый запрос страницы.Если файл прикреплен, он проверяет размер файла до того, как загрузка произойдет на вашу фактическую страницу ... работает как чемпион.
Мне это нужно было в VB, так что просто сделайте это и у вас ...сохранить вам преобразование;)
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim runtime As System.Web.Configuration.HttpRuntimeSection = System.Web.Configuration.WebConfigurationManager.GetSection("system.web/httpRuntime")
Dim maxRequestLength As Integer = (runtime.MaxRequestLength - 100) * 1024
Dim context As HttpContext = CType(sender, HttpApplication).Context
If context.Request.ContentLength > maxRequestLength Then
Dim pro As IServiceProvider = CType(context, 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
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("~/errorPages/MaxLength.htm")
End If
End If
End Sub