Tôi đang giới hạn người dùng kích thước tệp có thể tải lên trang web từ Web.config. Như được giải thích here, nó sẽ ném một ConfigurationErrorsException nếu kích thước không được chấp nhận. Tôi đã cố gắng để bắt nó từ các phương pháp hành động hoặc điều khiển cho các yêu cầu tải lên nhưng không có may mắn. Kết nối được đặt lại và tôi không thể hiển thị kết nối đó để hiển thị trang lỗi.Làm thế nào để bắt ConfigurationErrorsException cho vi phạm maxRequestLength?
Tôi đã cố gắng bắt nó trong sự kiện BeginRequest nhưng không có vấn đề gì tôi làm ngoại lệ là unhandled. Dưới đây là các mã:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
try
{
if (context.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[512];
// 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);
}
}
}
}
catch(HttpException)
{
context.Response.Redirect(this.Request.Url.LocalPath + "?action=exception");
}
}
Nhưng tôi vẫn có được điều này:
Maximum request length exceeded.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: Maximum request length exceeded.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Cập nhật:
phương pháp gì làm tăng ngoại lệ không? Nếu tôi đọc yêu cầu, nó làm tăng ngoại lệ Nếu tôi không đọc nó, tôi nhận được "101 Connection Reset" trong trình duyệt. Có thể làm gì ở đây?
Tôi muốn làm theo câu trả lời của bạn, tôi googled nó và thấy điều này: http://stackoverflow.com/questions/2966076/get-file-size-in-javascript. Theo chủ đề này, không có cách nào để tìm ra kích thước tệp thông qua Javascript đơn giản (tôi không muốn sử dụng Flash, ActiveX hoặc HTML 5!). Tôi có hiểu chính xác không? – celticharp
@necronio Tôi nghĩ vậy. –