private void Application_BeginRequest(Object source, EventArgs e) { IServiceProvider provider = HttpContext.Current as IServiceProvider; HttpWorkerRequest worker = provider.GetService(typeof(HttpWorkerRequest)) as HttpWorkerRequest; // Get the content length of the request, in bytes long nContentLength = Convert.ToInt64(worker.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentLength)); // Read MaxRequestLength from web.config of current website Configuration config = WebConfigurationManager.OpenWebConfiguration("/AdvancedWebSample"); HttpRuntimeSection configSection = config.GetSection("system.web/httpRuntime") as HttpRuntimeSection; // MaxRequestLength returns KB. Convert that to bytes. long nMaxContentLength = (long)configSection.MaxRequestLength * 1024; // In case of very large content length (e.g. 2 GB or more), HttpWorkerRequest gets mad and // returns negative value. So check for < 0 too. if (nContentLength < 0 || nContentLength > nMaxContentLength) { // Consuming the complete HTTP Request, before it reaches IIS, to avoid the Size Exception ReadAll(worker); //Redirect it to the error page (source as HttpApplication).Context.Response.Redirect("SizeErrorHandlerPage.aspx"); } }
/// <summary> /// Initializes this instance. /// </summary> public void Initialize() { AttachmentsDataGrid.Columns[0].HeaderText = GetLocalResourceObject("AttachmentsGrid.FileNameHeader.Text").ToString(); AttachmentsDataGrid.Columns[1].HeaderText = GetLocalResourceObject("AttachmentsGrid.SizeHeader.Text").ToString(); AttachmentsDataGrid.Columns[2].HeaderText = GetLocalResourceObject("AttachmentsGrid.Description.Text").ToString(); BindAttachments(); System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); HttpRuntimeSection section = config.GetSection("system.web/httpRuntime") as HttpRuntimeSection; double maxFileSize = Math.Round(section.MaxRequestLength / 1024.0, 1); FileSizeLimit.Text = string.Format("Make sure your file is under {0:0.#} MB.", maxFileSize); //check users role permission for adding an attachment if (!Page.User.Identity.IsAuthenticated || !UserManager.HasPermission(ProjectId, Common.Permission.AddAttachment.ToString())) { pnlAddAttachment.Visible = false; } if (!Page.User.Identity.IsAuthenticated || !UserManager.HasPermission(ProjectId, Common.Permission.DeleteAttachment.ToString())) { AttachmentsDataGrid.Columns[5].Visible = false; } }
public ActionResult Index(GlobalSettingModel model) { if (CurrentUser.UserRole == Enums.UserRole.Viewer || CurrentUser.UserRole == Enums.UserRole.Controller) { return(RedirectToAction("Index")); } Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); config.AppSettings.Settings["UseBackdate"].Value = model.UseBackDate.ToString(); config.AppSettings.Settings["SendXmlMasterData"].Value = model.IsSendXmlMasterData.ToString(); //model.UseBackDate = (bool.TrueString.ToLower() == config.AppSettings.Settings["UseBackdate"].Value.ToLower()); HttpRuntimeSection section = (HttpRuntimeSection)config.GetSection("system.web/httpRuntime"); if (model.FileSizeType == FileSizeType.MB) { section.MaxRequestLength = (int)(model.UploadFileSize * 1024f); } else { section.MaxRequestLength = model.UploadFileSize; } config.Save(ConfigurationSaveMode.Modified); //model.SizeType = fillSizeType(); //model.UploadFileSize = section.MaxRequestLength; return(RedirectToAction("Index")); }
public int GetMaxRequestLength() { Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); HttpRuntimeSection section = config.GetSection("system.web/httpRuntime") as HttpRuntimeSection; return section.MaxRequestLength; }
public static string GetMaxAllowedFileSize() { System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); HttpRuntimeSection section = config.GetSection("system.web/httpRuntime") as HttpRuntimeSection; return(string.Format("{0} kB", section.MaxRequestLength)); }
public static void EnsureRequestValidationMode() { try { if (Environment.Version.Major >= 4) { Type type = typeof(WebControl).Assembly.GetType("System.Web.Configuration.RuntimeConfig"); MethodInfo getConfig = type.GetMethod("GetConfig", BindingFlags.Static | BindingFlags.NonPublic, null, new Type[] { }, null); object runtimeConfig = getConfig.Invoke(null, null); MethodInfo getSection = type.GetMethod("GetSection", BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(string), typeof(Type) }, null); HttpRuntimeSection httpRuntimeSection = (HttpRuntimeSection)getSection.Invoke(runtimeConfig, new object[] { "system.web/httpRuntime", typeof(HttpRuntimeSection) }); FieldInfo bReadOnly = typeof(ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic); bReadOnly.SetValue(httpRuntimeSection, false); PropertyInfo pi = typeof(HttpRuntimeSection).GetProperty("RequestValidationMode"); if (pi != null) { Version version = (Version)pi.GetValue(httpRuntimeSection, null); Version RequiredRequestValidationMode = new Version(2, 0); if (version != null && !Version.Equals(version, RequiredRequestValidationMode)) { pi.SetValue(httpRuntimeSection, RequiredRequestValidationMode, null); } } bReadOnly.SetValue(httpRuntimeSection, true); } } catch { } }
internal void Load(string baseUri, ProxyAuthRequestResult par) { _svcBldr.Token = par.Token; EncryptedToken = par.Token; Options = par.Arguments; var svc = _svcBldr.BulkDataV2(); var sr = svc.GetBulkGuestData(); ExceptionsML.Check(sr.Error); var result = sr.Result; BulkData = JsonConvert.SerializeObject(sr); if (result.LicenseTokens != null) { Licenses = new List <TokenKey>((result.LicenseTokens)); } User = result.CurrentUser; CurrentUser = JsonConvert.SerializeObject(new { Name = result.CurrentUser.Username, Id = result.CurrentUser.Id }); CompanyName = result.CompanyName; HttpRuntimeSection httpRuntimeSection = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection; MaxRequestLength = httpRuntimeSection.MaxRequestLength; IsReadOnlyUser = result.CurrentUser.ReadOnlyUser; Version = Functions.GetVersion(); SystemPreferences = JsonConvert.SerializeObject(result.CompanySettings); var views = GetCachedViews(baseUri); CommonTemplates = JsonConvert.SerializeObject(views); }
void CheckWebConfig() { Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); object o = config.GetSection("system.web/httpRuntime"); HttpRuntimeSection section = o as HttpRuntimeSection; int max = section.MaxRequestLength; if (max < 10 * 1024) { section.MaxRequestLength = 40 * 1024; section.AppRequestQueueLimit = 5000; section.ExecutionTimeout = new TimeSpan(0, 0, 3000); config.Save(); ShowErrorLabel.InnerText = "原网站环境不支持大文件上传,现已更新为" + section.MaxRequestLength + "KB,请重新启动IIS!"; ShowErrorLabel.Style.Remove("display"); UploadButton.Enabled = false; DownloadInstallButton.Enabled = false; UpdateFileUpload.Enabled = false; CopyFilesButton.Enabled = false; //FinishButton.Disabled = true; } }
private double GetMaxFileSize() { System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); HttpRuntimeSection section = config.GetSection("system.web/httpRuntime") as HttpRuntimeSection; return(Math.Round(section.MaxRequestLength / 1024.0, 1)); }
/// <summary> /// Registers the startup script. /// </summary> private void RegisterStartupScript() { int?maxUploadBytes = null; try { HttpRuntimeSection section = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection; if (section != null) { // MaxRequestLength is in KB maxUploadBytes = section.MaxRequestLength * 1024; } } catch { // intentionally ignore and don't tell the fileUploader the limit } var postBackScript = this.FileUploaded != null?this.Page.ClientScript.GetPostBackEventReference(new PostBackOptions( this, "FileUploaded" ), true) : ""; postBackScript = postBackScript.Replace('\'', '"'); var script = string.Format( @" Rock.controls.fileUploader.initialize({{ controlId: '{0}', fileId: '{1}', fileTypeGuid: '{2}', hfFileId: '{3}', aFileName: '{4}', aRemove: '{5}', postbackScript: '{6}', fileType: 'file', isBinaryFile: '{7}', rootFolder: '{8}', uploadUrl: '{9}', submitFunction: function (e, data) {{ {10} }}, doneFunction: function (e, data) {{ {11} }}, maxUploadBytes: {12} }});", _fileUpload.ClientID, this.BinaryFileId, this.BinaryFileTypeGuid, _hfBinaryFileId.ClientID, _aFileName.ClientID, _aRemove.ClientID, postBackScript, this.IsBinaryFile ? "T" : "F", Rock.Security.Encryption.EncryptString(this.RootFolder), this.UploadUrl, this.SubmitFunctionClientScript, this.DoneFunctionClientScript, maxUploadBytes.HasValue ? maxUploadBytes.Value.ToString() : "null"); ScriptManager.RegisterStartupScript(_fileUpload, _fileUpload.GetType(), "FileUploaderScript_" + this.ClientID, script, true); }
private static HttpEncoder GetCustomEncoderFromConfig() { HttpRuntimeSection httpRuntime = RuntimeConfig.GetAppConfig().HttpRuntime; Type userBaseType = ConfigUtil.GetType(httpRuntime.EncoderType, "encoderType", httpRuntime); ConfigUtil.CheckBaseType(typeof(HttpEncoder), userBaseType, "encoderType", httpRuntime); return((HttpEncoder)HttpRuntime.CreatePublicInstance(userBaseType)); }
private static RequestValidator GetCustomValidatorFromConfig() { HttpRuntimeSection httpRuntime = RuntimeConfig.GetAppConfig().HttpRuntime; Type userBaseType = ConfigUtil.GetType(httpRuntime.RequestValidationType, "requestValidationType", httpRuntime); ConfigUtil.CheckBaseType(typeof(RequestValidator), userBaseType, "requestValidationType", httpRuntime); return((RequestValidator)HttpRuntime.CreatePublicInstance(userBaseType)); }
static HttpRuntime() { #if !TARGET_J2EE firstRun = true; try { WebConfigurationManager.Init(); #if MONOWEB_DEP SettingsMappingManager.Init(); #endif runtime_section = (HttpRuntimeSection)WebConfigurationManager.GetSection("system.web/httpRuntime"); } catch (Exception ex) { initialException = ex; } // The classes in whose constructors exceptions may be thrown, should be handled the same way QueueManager // and TraceManager are below. The constructors themselves MUST NOT throw any exceptions - we MUST be sure // the objects are created here. The exceptions will be dealt with below, in RealProcessRequest. queue_manager = new QueueManager(); if (queue_manager.HasException) { if (initialException == null) { initialException = queue_manager.InitialException; } else { Console.Error.WriteLine("Exception during QueueManager initialization:"); Console.Error.WriteLine(queue_manager.InitialException); } } trace_manager = new TraceManager(); if (trace_manager.HasException) { if (initialException == null) { initialException = trace_manager.InitialException; } else { Console.Error.WriteLine("Exception during TraceManager initialization:"); Console.Error.WriteLine(trace_manager.InitialException); } } registeredAssemblies = new SplitOrderedList <string, string> (StringComparer.Ordinal); cache = new Cache(); internalCache = new Cache(); internalCache.DependencyCache = internalCache; #endif do_RealProcessRequest = new WaitCallback(state => { try { RealProcessRequest(state); } catch {} }); end_of_send_cb = new HttpWorkerRequest.EndOfSendNotification(EndOfSend); }
static BaseResponseHeader() { #if NET_2_0 HttpRuntimeSection section = WebConfigurationManager.GetWebApplicationSection("system.web/httpRuntime") as HttpRuntimeSection; #else HttpRuntimeConfig section = HttpContext.GetAppConfig("system.web/httpRuntime") as HttpRuntimeConfig; #endif headerCheckingEnabled = section == null || section.EnableHeaderChecking; }
protected void Application_BeginRequest(object sender, EventArgs e) { HttpRuntimeSection section = WebConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection; if (Request.ContentLength > section?.MaxRequestLength * 1024) { Response.Redirect("~/Error/FileOverSize"); } }
/// <summary> /// Bind the MaxRequestLength and maxAllowedContentLength values from the web.config /// into the number boxes on the form. /// </summary> private void BindMaxFileSize() { HttpRuntimeSection section = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection; if (section != null) { // MaxRequestLength is in KB, so let's convert to MB for the users sake. numbMaxSize.Text = (section.MaxRequestLength / 1024).ToString(); } }
/// <summary> /// This Method running at Global.asax To Cath MaxRequestException /// and Redirect the user to RedirectPage /// </summary> /// <param name="sender"></param> /// <param name="RedirectPage"></param> public static void CatchMaxRequestLength(HttpApplication sender, string RedirectPage) { HttpRuntimeSection runTime = (HttpRuntimeSection) WebConfigurationManager.GetSection("system.web/httpRuntime"); //Approx 100 Kb(for page content) size has been deducted because //the maxRequestLength proprty is the page size, not only the file upload size int maxRequestLength = (runTime.MaxRequestLength - 100) * 1024; //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 = 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); } } context.Response.Redirect(RedirectPage); } }
/// <summary> /// Gets the maximum number of kilobytes the server can accept in the input type=file /// </summary> /// <returns></returns> private int GetMaxRequestLength() { HttpRuntimeSection section = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection; if (null != section) { return(section.MaxRequestLength); } return(0); }
protected int GetMaxRequestBytesLength() { // presume that the section is not defined in the web.config HttpRuntimeSection section = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection; if (section != null) { return(section.MaxRequestLength * 1024); } return(4096 * 1024); // 4mb by default }
// Summary: // Retrieves Max request length // // Returns: // Max request length in KiloBytes // Can be set on web.config : // <httpRuntime maxRequestLength="10240"/> in KB // protected int?GetMaxRequestLength() { int?maxRequestLength = null; HttpRuntimeSection section = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection; if (section != null) { maxRequestLength = section.MaxRequestLength; } return(maxRequestLength); }
public static int GetMaxRequestLength() { int maxRequestLength = 0; HttpRuntimeSection section = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection; if (section != null) { maxRequestLength = section.MaxRequestLength * 1024; } return(maxRequestLength); }
public static int GetMaxRequestLength() { //check size of image to be uplaoded. int maxRequestLength = 0; HttpRuntimeSection section = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection; if (section != null) { maxRequestLength = section.MaxRequestLength; } return(maxRequestLength); }
/// <summary> /// Updates this instance. /// </summary> public bool Update() { System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); HttpRuntimeSection section = config.GetSection("system.web/httpRuntime") as HttpRuntimeSection; HostSettingManager.UpdateHostSetting(HostSettingNames.AllowAttachments, AllowAttachments.Checked.ToString()); HostSettingManager.UpdateHostSetting(HostSettingNames.AttachmentStorageType, AttachmentStorageType.SelectedValue); HostSettingManager.UpdateHostSetting(HostSettingNames.AllowedFileExtensions, AllowedFileExtentions.Text.Trim()); HostSettingManager.UpdateHostSetting(HostSettingNames.FileSizeLimit, section.MaxRequestLength.ToString()); HostSettingManager.UpdateHostSetting(HostSettingNames.AttachmentUploadPath, txtUploadPath.Text.Trim().EndsWith(@"\") ? txtUploadPath.Text.Trim() : txtUploadPath.Text.Trim() + @"\"); return(true); }
/// <summary> /// Get from WebConfig MaxRequestLength /// </summary> /// <param name="ApplicationPath"></param> /// <returns></returns> private static int?MaxRequestLength(string ApplicationPath) { try { Configuration config = WebConfigurationManager.OpenWebConfiguration(ApplicationPath); HttpRuntimeSection section = config.GetSection("system.web/httpRuntime") as HttpRuntimeSection; return(section.MaxRequestLength); } catch { return(null); } }
private static int GetMaxFileSize() { try { Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~"); HttpRuntimeSection httpRuntimeSection = configuration.GetSection("system.web/httpRuntime") as HttpRuntimeSection; return(httpRuntimeSection.MaxRequestLength); } catch { return(-1); } }
// Token: 0x060020E6 RID: 8422 RVA: 0x000BD884 File Offset: 0x000BBA84 protected void RenderMaximumRequestLength(TextWriter writer) { int input = 4194304; System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~"); HttpRuntimeSection httpRuntimeSection = configuration.GetSection("system.web/httpRuntime") as HttpRuntimeSection; if (httpRuntimeSection != null) { input = httpRuntimeSection.MaxRequestLength * 1024; } RenderingUtilities.RenderInteger(writer, "a_iMaxRequestLength", input); }
/// <summary> /// Bind the MaxRequestLength and maxAllowedContentLength values from the web.config /// into the number boxes on the form. /// </summary> private void BindMaxFileSize() { HttpRuntimeSection section = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection; if (section != null) { // MaxRequestLength is in KB, so let's convert to MB for the users sake. numbMaxSize.Text = (section.MaxRequestLength / 1024).ToString(); // requestLengthDiskThreshold is in bytes and the MaxRequestLength must not be less than this value. //numbMaxSize.MinimumValue = Math.Round(section.RequestLengthDiskThreshold * 10.48576, 0 ).ToString(); //numbMaxSize.ToolTip = string.Format( "between {0} and {1} MB", section.RequestLengthDiskThreshold, numbMaxSize.MaximumValue ); } }
public static string GetMaxAllowedFileSize() { try { System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); HttpRuntimeSection section = config.GetSection("system.web/httpRuntime") as HttpRuntimeSection; return(string.Format("{0} kB", section.MaxRequestLength)); } catch (Exception Exc) { Exceptions.LogException(Exc); return("undefined"); } }
protected void Page_Load(object sender, EventArgs e) { string sErrorMessage = "It seems your file size limit has been reached. The limit for the combined size of all files is {0} MB. Click <a href='default.aspx'>here</a> to get back to the Comparison page and load a smaller file."; Configuration config = WebConfigurationManager.OpenWebConfiguration("/CompareServiceWeb"); HttpRuntimeSection configSection = config.GetSection("system.web/httpRuntime") as HttpRuntimeSection; // MaxRequestLength returns KB. Convert that to MB. int nMaxContentLength = configSection.MaxRequestLength / 1024; sErrorMessage = string.Format(sErrorMessage, nMaxContentLength); ErrorMessageSpan.InnerHtml = sErrorMessage; }
protected void Application_BeginRequest(object sender, EventArgs e) { //if (Request.Url.AbsolutePath.EndsWith("/")) //{ // // Server.Transfer(Request.Url.AbsolutePath + "Default.aspx"); //} HttpRuntimeSection runTime = (HttpRuntimeSection)WebConfigurationManager.GetSection("system.web/httpRuntime"); //Approx 100 Kb(for page content) size has been deducted because the maxRequestLength proprty is the page size, not only the file upload size int maxRequestLength = (runTime.MaxRequestLength - 100) * 1024; //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. context.Response.Redirect("~/Error/AttachError.aspx", true); } }