How to Increase the max upload file size in ASP.NET MVC
By FoxLearn Published on Feb 18, 2024 399
By default, you only upload up to 4MB (4096 KB) when hosting your website on IIS.
To increase file size when uploading on IIS 7 you need to open the web.config file, then add the configuration as below.
<system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="52428800" /> </requestFiltering> </security> </system.webServer>
As you can see, I have increased the max file upload size to 50MB. You can also increase the maximun upload file size by creating a custom file size attribute as shown below.
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Web; using System.Web.Mvc; namespace Customs { [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class FileSizeAttribute : ValidationAttribute, IClientValidatable { public int? MaxBytes { get; set; } public FileSizeAttribute(int maxBytes) : base("Please upload a supported file.") { MaxBytes = maxBytes; if (MaxBytes.HasValue) ErrorMessage = $"Please upload a file of less than {MaxBytes.Value} bytes."; } public override bool IsValid(object value) { HttpPostedFileBase file = value as HttpPostedFileBase; if (file != null) { bool result = true; if (MaxBytes.HasValue) result &= (file.ContentLength < MaxBytes.Value); return result; } return true; } IEnumerable<ModelClientValidationRule> IClientValidatable.GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule { ValidationType = "filesize", ErrorMessage = FormatErrorMessage(metadata.DisplayName) }; rule.ValidationParameters["maxbytes"] = MaxBytes; yield return rule; } } }
Open the FilterConfig.cs file, then add FileSizeAttribute to the RegisterGlobalFilters method that lets you filter the upload file size to IIS.
using System.Web; using System.Web.Mvc; namespace CSharpCode { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new FileSizeAttribute()); } } }
- Essential Tips for Securing Your ASP.NET Website
- Top Security Best Practices for ASP.NET
- Boost Your ASP.NET Core Website Performance with .NET Profiler
- The name 'Session' does not exist in the current context
- Implementing Two-Factor Authentication with Google Authenticator in ASP.NET Core
- How to securely reverse-proxy ASP.NET Core
- How to Retrieve Client IP in ASP.NET Core Behind a Reverse Proxy
- Only one parameter per action may be bound from body in ASP.NET Core
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
Dec 19, 2024
AdminKit Bootstrap 5 HTML5 UI Kits Template
Nov 17, 2024
RuangAdmin Template
Nov 13, 2024
Admin BSB Free Bootstrap Admin Dashboard
Nov 14, 2024