2010-09-08 35 views

Respuesta

41

Añadir lo siguiente a su archivo web.config:

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

Esto establece a 2 GB. No estoy seguro de cuál es el máximo.

+3

Asegúrese de agregar esto al 'Web.config' principal en lugar del que está dentro de la carpeta' Views' ... –

+3

sí, pero ¿cómo atrapar esta excepción? Establecer maxRequestLength en 2 GB, creo que no es el mejor choise .... – MDDDC

+0

¡Salvó mi día! ¡Gracias hombre! – Flappy

20

se puede aumentar la longitud máxima de las solicitudes en web.config, bajo <system.web>:

<httpRuntime maxRequestLength="100000" /> 

En este ejemplo se establece el tamaño máximo de 100 MB  .

7

Esa no es una manera excelente de hacerlo, ya que básicamente estás abriendo tu servidor al DoS attacks permitiendo a los usuarios enviar archivos inmensos. Si sabe que el usuario solo debe cargar imágenes de un determinado tamaño, debe aplicarlas en lugar de abrir el servidor para envíos aún más grandes.

Para hacer eso, puede usar el siguiente ejemplo.

Como me han gritado por publicar un enlace, he agregado lo que finalmente implementé usando lo que aprendí del enlace que publiqué anteriormente, y esto ha sido probado y funciona en mi propio sitio ... asume un límite predeterminado de 4   MB. Puede implementar algo como esto, o alternativamente emplear algún tipo de control ActiveX de terceros.

Tenga en cuenta que en este caso redirecciono al usuario a la página de error si su envío es demasiado grande, pero no hay nada que le impida personalizar esta lógica más si así lo desea.

Espero que sea útil.

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); 
     } 
    } 
Cuestiones relacionadas