111,126
社区成员
发帖
与我相关
我的任务
分享
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpRuntimeSection runTime = (HttpRuntimeSection)WebConfigurationManager.GetSection("system.web/httpRuntime");
int maxRequestLength = (runTime.MaxRequestLength - 100) * 1024;
HttpContext context = ((HttpApplication)sender).Context;
if (Request.ContentLength > maxRequestLength)
{
IServiceProvider provider = (IServiceProvider)context;
HttpWorkerRequest workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
// Check if body contains data
if (workerRequest.HasEntityBody())
{
// get the total body length
int requestLength = 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 (requestLength - receivedBytes >= initialBytes)
{
// Read another set of bytes
initialBytes = workerRequest.ReadEntityBody(buffer, buffer.Length);
// Update the received bytes
receivedBytes += initialBytes;
}
initialBytes = workerRequest.ReadEntityBody(buffer, requestLength - receivedBytes);
}
}
}
}
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
if (ex.InnerException != null && ex.InnerException.Message.Contains("Maximum request length exceeded"))
{
Server.ClearError();
Response.Redirect("~/FileTooLarge.aspx");
}
}