现在的位置: 首页 > 综合 > 正文

截获asp.net上传文件过大IIS报错的Httpmodule代码 –方便以后使用

2012年11月18日 ⁄ 综合 ⁄ 共 2053字 ⁄ 字号 评论关闭
public class UpLoadHttpModule : IHttpModule
{
    
// Methods
    private void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpRequest request 
= HttpContext.Current.Request;
        
if (request.ContentLength > 0x400000)
        {
            HttpApplication app 
= sender as HttpApplication;
            HttpContext context 
= app.Context;
            
try
            {
                HttpWorkerRequest wr 
= (HttpWorkerRequest) context.GetType().GetProperty("WorkerRequest", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(context, null);
                
if (wr.HasEntityBody())
                {
                    
int contentlen = Convert.ToInt32(wr.GetKnownRequestHeader(11));
                    
byte[] buffer = wr.GetPreloadedEntityBody();
                    
int received = 0;
                    
if (buffer != null)
                    {
                        received 
= buffer.Length;
                    }
                    
int totalrecv = received;
                    
if (!wr.IsEntireEntityBodyIsPreloaded())
                    {
                        buffer 
= new byte[0xffff];
                        
while ((contentlen - totalrecv) >= received)
                        {
                            received 
= wr.ReadEntityBody(buffer, buffer.Length);
                            totalrecv 
+= received;
                        }
                        received 
= wr.ReadEntityBody(buffer, contentlen - totalrecv);
                    }
                }
                context.Response.Redirect(
"error.aspx" + request.Url.Query + "");
            }
            
catch (Exception)
            {
                context.Response.Redirect(
"error.aspx" + request.Url.Query + "");
            }
        }
    }

    private void application_EndRequest(object sender, EventArgs e)
    {
    }
    
public void Dispose()
    {
    }
    
public void Init(HttpApplication application)
    {
        application.BeginRequest 
+= new EventHandler(this.Application_BeginRequest);
        application.EndRequest 
+= new EventHandler(this.application_EndRequest);
    }
}

抱歉!评论已关闭.