try/catch
HandleErrorAttribute
global.asax
Application_Error
protected void Application_Error(object sender, EventArgs e) { try { if (IsMaxRequestExceededException(this.Server.GetLastError())) { this.Server.ClearError(); HttpContext.Current.ClearError(); /* NOTE: Because of the special context we're in, Server.Execute and Server.Transfer * won't work on the next line. */ Response.Redirect("~/Home/UploadTooBig"); } } catch (Exception ex) { throw; } } const int TimedOutExceptionCode = -2147467259; private static bool IsMaxRequestExceededException(Exception e) { // unhandled errors = caught at global.ascx level // http exception = caught at page level Exception main; var unhandled = e as HttpUnhandledException; if (unhandled != null && unhandled.ErrorCode == TimedOutExceptionCode) { main = unhandled.InnerException; } else { main = e; } var http = main as HttpException; if (http != null && http.ErrorCode == TimedOutExceptionCode) { // hack: no real method of identifying if the error is max request exceeded as // it is treated as a timeout exception if (http.StackTrace.Contains("GetEntireRawContent")) { // MAX REQUEST HAS BEEN EXCEEDED return true; } } return false; }
public class UploadTooBigViewModel { public UploadTooBigViewModel() { MaxRequestLength = GetMaxRequestLength(); } public string MaxRequestLength { get; private set; } private string GetMaxRequestLength() { const int DEFAULT_VALUE = 4096; int byteQty = DEFAULT_VALUE; var fileSpec = HttpContext.Current.Server.MapPath("~/web.config"); if (System.IO.File.Exists(fileSpec)) { var contents = System.IO.File.ReadAllText(fileSpec); var doc = new System.Xml.XmlDocument(); /* We'll assume the web.config file is a valid XML document. We wouldn't have made it * this far otherwise. */ doc.LoadXml(contents); var xPath = "//configuration/system.web/httpRuntime/@maxRequestLength"; var node = doc.SelectSingleNode(xPath); byteQty = node == null ? DEFAULT_VALUE : int.Parse(node.Value); } var result = ReduceBytes(byteQty * 1024); return result; } private string ReduceBytes(int byteQty) { float byteResult = byteQty; const string PREFIX = " KMGTPEZY"; var index = 0; while (byteResult > 1024) { byteResult /= 1024F; index++; } var result = byteResult.ToString("#,##0.0") + " " + PREFIX.Substring(index, 1) + "B"; return result; } }
HomeController
public ActionResult UploadTooBig() { return View(new UploadTooBigViewModel()); }
HomeController.UploadToBig
@model MyWebsite.Models.UploadTooBigViewModel @{ ViewBag.Title = "Upload Too Large"; Layout = "~/Views/Shared/_Layout.cshtml"; } <p>You cannot upload a file that large. The largest file that can be uploaded is @Model.MaxRequestLength</p> <a href="javascript:history.go(-1);">Back</a>
ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.