In this blog post, Haissam Abdul Malak will create an HttpModule which check if the file is larger than 4 MB to redirect the user to a webform "Error.aspx".
The module will register to the BeginRequest event to execute the needed code
Below is the implementation
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
namespace HAMModule
{
public class MyModule : IHttpModule
{
public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(app_BeginRequest);
}
void app_BeginRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
if (context.Request.ContentLength > 4096000)
{
IServiceProvider provider = (IServiceProvider)context;
HttpWorkerRequest wr = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
// Check if body contains data
if (wr.HasEntityBody())
{
// get the total body length
int requestLength = wr.GetTotalEntityBodyLength();
// Get the initial bytes loaded
int initialBytes = wr.GetPreloadedEntityBody().Length;
if (!wr.IsEntireEntityBodyIsPreloaded())
{
byte[] buffer = new byte[512000];
// Set the received bytes to initial bytes before start reading
int receivedBytes = initialBytes;
while (requestLength - receivedBytes >= initialBytes)
{
// Read another set of bytes
initialBytes = wr.ReadEntityBody(buffer, buffer.Length);
// Update the received bytes
receivedBytes += initialBytes;
}
initialBytes = wr.ReadEntityBody(buffer, requestLength - receivedBytes);
}
}
// Redirect the user to an error page.
context.Response.Redirect("Error.aspx");
}
}
public void Dispose()
{
}
}
}
Now all you need to do is to add the module in the web.config file by adding the below entry under system.Web
Hope this helps,
No comments:
Post a Comment