Cancel a file upload RRS feed

  • Question

  • User-1485845807 posted


    I'm making use of a HttpModule to intercept a user uploading a file. I need to check the file size and then redirect if its over a certain limit. In the code below I am able to check the file size, but the redirect does not seem to happen immediately. The browser seems to 'hang' for some time before redirecting. I think that it is trying to upload the file.

    Is there a way I  can cancel the upload and redirect without causing the browser to hang?

    void context_BeginRequest(object sender, EventArgs e)

                HttpApplication httpApplication = (HttpApplication)sender;
                HttpContext context = httpApplication.Context;

                string httpUrl = context.Request.Url.ToString();
                if (!httpUrl.ToLower().Contains("/upload.aspx"))

                if (context.Request.ContentType.IndexOf("multipart/form-data") == -1)
                // Get the worker request object. This object provides us with the byte data  as the user is uploading it.  
                // This is a very critical part of this module.
                HttpWorkerRequest workerRequest = (HttpWorkerRequest)context.GetType().GetProperty("WorkerRequest",  BindingFlags.Instance | BindingFlags.NonPublic).GetValue(context, null);

                // Indicates if the worker request has a body
                if (workerRequest.HasEntityBody())
                    // Get the byte size of the form post. We need this to detect how much we have left to go.
                    long contentLength = long.Parse((workerRequest.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentLength)));
                    if (contentLength > 1024 * 1024 )

    Thursday, July 30, 2009 7:41 PM


  • User-1704836357 posted


    I think that's not possible the way you try it. I am not sure, but I think that at the Begin_Request the whole content has already been loaded. Possiblethe WorkerRequest does that. Try to do the following to test it: remove the workerrequest part and just redirect to test if it takes as long as before. if it does, its not the problem. if its faster, you can try to do the following:

    StreamReader reader = new StreamReader(app.Request.InputStream);

    then read each line and check if you exceeded the max filesize. Okay, this would not be the size of the file, but the whole request, but it should work. 


    You also can try to add the follwoing to your web.config.


        <httpRuntime maxRequestLength="1024" />


    THe size in KB, default is 4 MB. In that case that would be 1 MB. Maximum is 100 MB.


    Hope that helps,

    Bernhard Kircher


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 31, 2009 3:57 AM