如何解决“超出最大请求长度”异常?

时间:2010-09-08 13:23:19

标签: asp.net

当我上传图片时出现此错误:

  

超出最大请求长度

如何解决此问题?

4 个答案:

答案 0 :(得分:55)

将以下内容添加到您的web.config文件中:

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

这将它设置为2GB。不确定最大值是什么。

答案 1 :(得分:21)

您可以在<system.web>

下的web.config中增加请求的最大长度
<httpRuntime maxRequestLength="100000" />

此示例将最大大小设置为100 MB。

答案 2 :(得分:9)

这不是一个很好的方法,因为你基本上打开你的服务器DoS attacks,允许用户提交巨大的文件。如果您知道用户应该只上传特定大小的图像,那么您应该强制执行该操作,而不是将服务器打开以进行更大规模的提交。

为此,您可以使用以下示例。

由于我一直呻吟着发布一个链接,我已经添加了我最终使用我从之前发布的链接中学到的东西 - 这已经过测试并在我自己的网站上运行...它假设一个默认限制为4 MB。你可以实现这样的东西,或者使用某种第三方ActiveX控制。

请注意,在这种情况下,如果用户提交的内容太大,我会将用户重定向到错误页面,但如果您愿意,则无​​法阻止您进一步自定义此逻辑。

我希望它有用。

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

答案 3 :(得分:0)

为避免超出最大请求长度,请不要上传大尺寸图片或将图片大小减小100kb至200kb之间。