問題描述
我搜索了 SO,發現 這個問題,但這不是我要問的.我想知道是否可以創建一個可以檢查請求的 ContentLength 的 IHttpModule,如果可以,則重定向或以某種方式拋出該請求并創建一個新請求.
I searched SO and found this question, but it's not quite what I'm asking. I'm wondering if a IHttpModule can be created that can inspect the ContentLength of the request, and if so either redirect or somehow throw that request out and create a new one.
具體來說,我正在嘗試處理圖像文件上傳,但我想讓請求繼續到上傳頁面并發出某種警告,而不是一個簡單的錯誤頁面.我有這段代碼會受到很大的請求:
Specifically, I'm trying to handle image file uploads, but I'd like to have the request continue on to the upload page with some kind of warning, rather than a flat error page. I have this bit of code that gets hit with a large request:
private void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
if (context.Request.ContentLength > (4 * 1024 * 1024))
{
}
}
執行路徑按照我的意愿進入這個 IF 塊.但從這里開始,我真的不知道該去哪里.這是一個不好的方法嗎?
The execution path enters this IF block like I want it to. But from here, I'm not really sure where to go. Is this a bad approach?
按原樣(沒有此模塊),Fiddler 報告 IIS 正在返回 500 代碼.我想避免這種情況,并讓代碼從請求的頁面返回 200,就像我說的那樣發出警告.
As it is (without this module), Fiddler is reporting that IIS is returning a 500 code. I'd like to avoid this and have the code return a 200 from the requested page, just with the warning like I said.
推薦答案
由于 HTTP 的性質,在讀取所有請求數據之前,您實際上無法返回任何內容.當您收到超大請求時,您有兩種選擇:
Because of the nature of HTTP, you can't actually return anything until you read all the request data. When you receive an oversized request, you have two options:
- 讀入所有數據,然后返回一個漂亮的錯誤頁面.這聽起來不錯,但意味著用戶必須等待上傳完成才能收到他無法上傳的消息.它還打開了一個可能的 DOS 攻擊漏洞
- 立即終止請求.這會給用戶一個糟糕的斷開連接頁面,但保留了安全性.
還有第三種選擇——使用一個高級組件,它提供了很好的錯誤消息和安全性.您可以只使用 Flash 組件,而且其中有很多組件,但是當然,如??果用戶沒有 Flash,那您就不走運了.
There is a third option -- use an advanced component that provides both nice error messages as well as security. You can use flash only components, and there are many of them out there, but of course, if the user doesn't have flash, you're out of luck.
這篇關于上傳超過 Asp.net 請求長度限制的文件?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!