Suppose someone:

  1. visits and ASPX page (http get request).
  2. sets a "too large" file in a file uploader and clicks the upload button (http post request).

I don't care to have a custom error page served; that's dumb, and disrupts the application.

I want to HANDLE the error programmatically. It can be intercepted (after the entire request has been received, I think) by the Application_BeginRequest handler of global.asax, as posted here.

What I'd like to do is remove the oversized file from the request, set some kind of flag in something like "HttpContext.Current.Items["filetoolarge"] = true", then do a Server.Transfer to the same page, so that the request runs as though the file was never sent, except now there's this error flag that the page would of course check and display a nice error message when found.

Can this be done?

3

There are 3 best solutions below

0
On BEST ANSWER

I posted the solution here: Where do I catch and handle maxAllowedContentLength exceeded in IIS7?

My solution involves overriding the page's OnError handler, and I think it works only in .NET 4.0, because it involves getting the last exception as an HttpException and checking the WebEventCode property, which seems to be new in the .NET 4.0 framework.

There is another solution there that involves intercepting the Application_EndRequest global application handler, where both the StatusCode and SubStatusCode property values are available, but I don't think it works, because the response has probably already been flushed to the client by the time the EndRequest event is raised.

From my experience, both the OnError and Application_EndRequest methods run almost immediately, long before the server could have possibly received the entire request, so it probably gets fired as a result of some early warning about the request size.

I have tested the OnError method, and it works flawlessly, aside from the unavoidable delay where the browser insists on finishing the upload of its request before handling and displaying the server's response.

Information on Web Event Codes can be found here - http://msdn.microsoft.com/en-us/library/ff650306.aspx

3
On

The only way I know how to do this without using Flash or ActiveX is to set the maxRequestLength to a high value, and then use JavaScript to access the information about the file once it becomes available, and then handle cancelling/error handling. I used the Telerik upload control to do it, but you should be able to do something similar.

1
On

Set maxRequestLength in your web.config to a big value like this:

<system.web>
        <httpRuntime maxRequestLength="26000" executionTimeout="600"/>
</system.web>

so you can receive the big file. and then process it like this:

        If fileUploader.PostedFile.ContentLength > theSize Then
            'show error'
        else
            'process it'
        End If

Hope it helps.

UPDATE:

maxRequestLength is in KB.

PostedFile.ContentLength is in bytes.