2010-09-08 11 views
20

Quando ho caricare un'immagine che ho avuto questo errore:Come si risolve l'eccezione "lunghezza massima richiesta superata"?

maximum request length exceeded

Come posso risolvere questo problema?

+1

Eventuali duplicati di [lunghezza richiesta massima superata] (http://stackoverflow.com/questions/3853767/maximum-request-length-exceeded) – niico

+0

Come Niico ha detto, per esempio, se si utilizza più di una riga in Web.config, potresti ricevere questo errore. – oguzhan

risposta

41

Aggiungere il seguente al file web.config:

<configuration> 
    <system.web> 
     <httpRuntime maxRequestLength ="2097151"/> 
    </system.web> 
</configuration> 

Questa imposta a 2GB. Non so quale sia il massimo.

+3

Assicurati di aggiungerlo al file principale "Web.config" anziché quello all'interno della cartella 'Views' ... –

+3

sì, ma come rilevare questa eccezione Impostare maxRequestLength su 2 GB Penso che non sia il migliore choise .... – MDDDC

+0

Salvato la mia giornata! Grazie uomo! – Flappy

20

è possibile aumentare la lunghezza massima di richieste nel web.config, sotto <system.web>:

<httpRuntime maxRequestLength="100000" /> 

Questo esempio imposta la dimensione massima di 100 MB  .

7

Questo non è un modo fantastico per farlo poiché in pratica stai aprendo il tuo server a DoS attacks consentendo agli utenti di inviare file immensi. Se sai che l'utente dovrebbe caricare solo immagini di una certa dimensione, dovresti applicarla piuttosto che aprire il server a invii ancora più grandi.

Per fare ciò è possibile utilizzare l'esempio di seguito.

Come mi è stato lamentato per aver postato un link, ho aggiunto ciò che ho implementato in ultima analisi usando quello che ho imparato dal link che ho postato in precedenza - e questo è stato testato e funziona sul mio sito ... presume un limite predefinito di 4   MB. È possibile implementare qualcosa di simile o in alternativa utilizzare una sorta di controllo ActiveX di terze parti.

Nota che in questo caso reindirizzo l'utente alla pagina di errore se il loro invio è troppo grande, ma non c'è nulla che ti impedisca di personalizzare ulteriormente questa logica se lo desideri.

Spero sia utile.

public class Global : System.Web.HttpApplication { 
    private static long maxRequestLength = 0; 

    /// <summary> 
    /// Returns the max size of a request, in kB 
    /// </summary> 
    /// <returns></returns> 
    private long getMaxRequestLength() { 

     long requestLength = 4096; // Assume default value 
     HttpRuntimeSection runTime = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection; // check web.config 
     if(runTime != null) { 
      requestLength = runTime.MaxRequestLength; 
     } 
     else { 
      // Not found...check machine.config 
      Configuration cfg = ConfigurationManager.OpenMachineConfiguration(); 
      ConfigurationSection cs = cfg.SectionGroups["system.web"].Sections["httpRuntime"]; 
      if(cs != null) { 
       requestLength = Convert.ToInt64(cs.ElementInformation.Properties["maxRequestLength"].Value); 
      } 
     } 
     return requestLength; 
    } 

    protected void Application_Start(object sender, EventArgs e) { 
     maxRequestLength = getMaxRequestLength(); 
    } 

    protected void Application_End(object sender, EventArgs e) { 

    } 

    protected void Application_Error(object sender, EventArgs e) { 
     Server.Transfer("~/ApplicationError.aspx"); 
    } 

    public override void Init() { 
     this.BeginRequest += new EventHandler(Global_BeginRequest); 
     base.Init(); 
    } 

    protected void Global_BeginRequest(object sender, EventArgs e) { 

     long requestLength = HttpContext.Current.Request.ContentLength/1024; // Returns the request length in bytes, then converted to kB 

     if(requestLength > maxRequestLength) { 
      IServiceProvider provider = (IServiceProvider)HttpContext.Current; 
      HttpWorkerRequest workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest)); 

      // Check if body contains data 
      if(workerRequest.HasEntityBody()) { 

       // Get the total body length 
       int bodyLength = workerRequest.GetTotalEntityBodyLength(); 

       // Get the initial bytes loaded 
       int initialBytes = 0; 
       if(workerRequest.GetPreloadedEntityBody() != null) { 
        initialBytes = workerRequest.GetPreloadedEntityBody().Length; 
       } 
       if(!workerRequest.IsEntireEntityBodyIsPreloaded()) { 
        byte[] buffer = new byte[512000]; 

        // Set the received bytes to initial bytes before start reading 
        int receivedBytes = initialBytes; 
        while(bodyLength - receivedBytes >= initialBytes) { 

         // Read another set of bytes 
         initialBytes = workerRequest.ReadEntityBody(buffer, buffer.Length); 

         // Update the received bytes 
         receivedBytes += initialBytes; 
        } 
        initialBytes = workerRequest.ReadEntityBody(buffer, bodyLength - receivedBytes); 
       } 
      } 

      try { 
       throw new HttpException("Request too large"); 
      } 
      catch { 
      } 

      // Redirect the user 
      Server.Transfer("~/ApplicationError.aspx", false); 
     } 
    } 
Problemi correlati