How to Increase the max upload file size in ASP.NET MVC

By FoxLearn 2/18/2024 1:23:33 AM   66
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());
        }
    }
}