2011-08-05 29 views
2

當我上傳一個文件在我的MVC網站,我正在尋找處理上傳失敗,由於用戶超過maxRequestLength比例如顯示一個通用的自定義錯誤頁面更優雅。我希望顯示他們試圖發佈的相同頁面,但會收到一條消息,通知他們他們的文件太大了......類似於他們在驗證錯誤時可能得到的內容。ASP.NET MVC:處理上傳超過maxRequestLength

我開始的想法從這樣一個問題:

Catching "Maximum request length exceeded"

但我想要做的是,而不是轉移到一個錯誤頁面(因爲他們在這個問題做),我想用手處理掉原來的控制器,但是在ModelState中添加了一個錯誤來指出問題。以下是一些代碼,其中的註釋說明了我想要做什麼以及想要做什麼。有關IsMaxRequestExceededEexception的定義,請參閱上面的問題,這有點破解,但我沒有找到更好的結果。

我註釋掉線用戶返回到正確的頁面,當然他們失去了他們可能做出的任何改變,我不希望使用重定向這裏...

if (IsMaxRequestExceededException(Server.GetLastError())) 
{ 
    Server.ClearError(); 
    //((HttpApplication) sender).Context.Response.Redirect(Request.Url.LocalPath + "?maxLengthExceeded=true"); 
    // TODO: Replace above line - instead tranfer processing to appropriate controlller with context intact, etc 
    // but with an extra error added to ModelState. 
} 

只是尋找想法而不是完整的解決方案;我試圖做的甚至可能嗎?

回答

0

下面是一種解決方法:將web.config中的maxRequestLength屬性設置爲某個較高值。然後寫一個自定義的驗證屬性:

public class MaxFileSize : ValidationAttribute 
{ 
    public int MaxSize { get; private set; } 

    public MaxFileSize(int maxSize) 
    { 
     MaxSize = maxSize; 
    } 

    public override bool IsValid(object value) 
    { 
     var file = value as HttpPostedFileBase; 
     if (file != null) 
     { 
      return file.ContentLength < MaxSize; 
     } 
     return true; 
    } 
} 

它可以用來裝飾您的視圖模型:

public class MyViewModel 
{ 
    [Required] 
    [MaxFileSize(1024 * 1024, ErrorMessage = "The uploaded file size must not exceed 1MB")] 
    public HttpPostedFileBase File { get; set; } 
} 

,那麼你可以有一個控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     var model = new MyViewModel(); 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(MyViewModel model) 
    { 
     if (!ModelState.IsValid) 
     { 
      return View(model); 
     } 

     // TODO: Process the uploaded file: model.File 

     return RedirectToAction("Success"); 
    } 
} 

最後一個視圖:

@model MyViewModel 

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    <div> 
     @Html.LabelFor(x => x.File) 
     <input type="file" name="file" /> 
     @Html.ValidationMessageFor(x => x.File) 
    </div> 

    <p><input type="submit" value="Upload"></p> 
}