Al cargar una imagen que tenía este error:¿Cómo puedo resolver la excepción de "longitud de solicitud máxima excedida"?
maximum request length exceeded
¿Cómo puedo solucionar este problema?
Al cargar una imagen que tenía este error:¿Cómo puedo resolver la excepción de "longitud de solicitud máxima excedida"?
maximum request length exceeded
¿Cómo puedo solucionar este problema?
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.
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 .
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);
}
}
duplicado posible de [petición longitud máxima superada] (http://stackoverflow.com/questions/3853767/maximum-request-length-exceeded) – niico
Como Niico dijo, por ejemplo, si se utiliza más de una línea en Web.config, puede obtener ese error. –
oguzhan