需要在网站中上传文件,但是当文件大小太大的时候IIS会拒绝连接,导致用户看到不友好的错误界面。
解决方法
1.服务器端处理
在globle.asax中的protected void Application_Error(object sender, EventArgs e)函数中处理错误
public class Global : System.Web.HttpApplication { static List<string[]> options; static Global(){ var mlstr = WebConfigurationManager.AppSettings.Get("MaxRequestLength"); if (string.IsNullOrEmpty(mlstr)) options = null; else { try { var optionstr = mlstr.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries); options = new List<string[]>(); optionstr.ToList().ForEach(e => options.Add(e.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries))); } catch(Exception e) { options = null; } } } ... protected void Application_Error(object sender, EventArgs e) { if (Server.GetLastError().GetType() != typeof(HttpException)) return; if (options == null) return; var item = options.Find(i => i[0] == this.Request.Url.LocalPath); if (item == null) return; int maxRequestLength = 0; Int32.TryParse(item[1], out maxRequestLength); //This code is used to check the request length of the page and if the request length is greater than //MaxRequestLength then retrun to the same page with extra query string value action=exception HttpContext context = ((HttpApplication)sender).Context; 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[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); } } //Redirect the user to the same page with querystring action=exception. //Response.ClearContent(); //context.Server.ClearError(); context.Response.Redirect(this.Request.Url.LocalPath + "?" + item[2]); } } ... }