1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| public class UploadHttpModule : IHttpModule
{
/// <summary>
/// Initialize the HttpModule
/// </summary>
/// <param name="context"></param>
void IHttpModule.Init(HttpApplication context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
context.BeginRequest += OnBeginRequest;
}
private void OnBeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
if (app != null)
{
if (app.Request.ContentType.StartsWith("multipart/form-data") && app.Request.ContentLength > 0)
{
int fileSize = app.Request.ContentLength;
HttpRuntimeSection httpRuntimeSection = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
int httpMaxSize = httpRuntimeSection.MaxRequestLength;
if (fileSize > httpMaxSize * 1024)
{
int maxRequestLengthExceeded = 1;
//throw new ApplicationException("File too big");
StringBuilder redirectUrl = new StringBuilder(app.Request.Url.AbsolutePath);
redirectUrl.Append("?");
for (int i = 0; i < app.Request.QueryString.Count; i++)
{
if (app.Request.QueryString.Keys[i] != "maxRequestLengthExceeded")
{
redirectUrl.Append(app.Request.QueryString.Keys[i]);
redirectUrl.Append("=");
redirectUrl.Append(app.Request.QueryString[i]);
redirectUrl.Append("&");
}
else
{
int.TryParse(app.Request.QueryString[i], out maxRequestLengthExceeded);
maxRequestLengthExceeded++;
}
}
redirectUrl.Append("maxRequestLengthExceeded=");
redirectUrl.Append(maxRequestLengthExceeded.ToString());
app.Response.Redirect(redirectUrl.ToString());
}
}
}
}
void IHttpModule.Dispose()
{
//nothing to do
}
} |
Partager