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

Myw*_*rld 27 asp.net

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

超出最大请求长度

我该如何解决这个问题?

kd7*_*kd7 55

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

<configuration>
   <system.web>
      <httpRuntime maxRequestLength ="2097151"/>
   </system.web>
</configuration>
Run Code Online (Sandbox Code Playgroud)

这将它设置为2GB.不确定最大值是多少.

  • 确保你将它添加到主`Web.config`而不是`Views`文件夹中的那个... (4认同)
  • 是但是如何捕获此异常?将maxRequestLength设置为2 GB我认为不是最好的选择.... (3认同)

Phi*_*ert 21

您可以在web.config中增加请求的最大长度,位于<system.web>:

<httpRuntime maxRequestLength="100000" />
Run Code Online (Sandbox Code Playgroud)

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


小智 9

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

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

由于我一直呻吟着张贴链接,我已经添加了我最终使用我从之前发布的链接中学到的内容 - 这已经过测试并在我自己的网站上运行...它假设默认限制为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);
        }
    }
Run Code Online (Sandbox Code Playgroud)