上传文件太大(处理)

首先,在Global.asax.cs中实现Application_BeginRequest方法,实例HttpWorkerRequest wr = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest))来获取web.config中的maxLength长度,同时开辟一个内存wr(大小为maxLength);然后用GetPreloadedEntityBody()方法获取上传的文件的内容。对文件内容长度进行判断,如果文件大于2MB(request.ContentLength > 2097152),则用ReadEntityBody()方法读取文件的n个字符,读入wr中,当读入的数据〉wr的大小时,Maximum request length exceeded异常触发。
于是在Global.asax.cs中实现Application_Error方法,判断如果获得的异常type为Maximum request length exceeded,则定位到错误页面(Error.asp)页面内容“上传的文件太大”。


 void Application_BeginRequest(object source, EventArgs e)
        {
              IServiceProvider provider = (IServiceProvider) HttpContext.Current;
              HttpWorkerRequest wr = (HttpWorkerRequest) provider.GetService(typeof(HttpWorkerRequest));
              byte[] bs = wr.GetPreloadedEntityBody();
             
              HttpRequest request = HttpContext.Current.Request;
              if (request.ContentLength > 2097152)
              {
                  if (!wr.IsEntireEntityBodyIsPreloaded())
                  {
                      int n = 65535;
                      byte[] bs2 = new byte[n];
                      while (wr.ReadEntityBody(bs2, n) > 0)
                      {
                      }

                  }
                  //Response.Redirect("~/About.aspx");
              }
        }

 


 void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs
            Exception exc = Server.GetLastError();
 
            // Handle HTTP errors
            if (exc.GetType() == typeof(HttpUnhandledException))
            {
                if (exc.InnerException.Message.Contains("Maximum request length exceeded."))
                    Response.Redirect("~/Error.aspx");

                //exc.InnerException.
            }
        }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值