How to Restrict Uploaded File Size in ASP.NET Core MVC

SPONSOR AD

How to Restrict Uploaded File Size in ASP.NET Core MVC:

In this article, I will discuss How to Restrict Uploaded File Size in an ASP.NET Core MVC Application with Examples. Please read our previous article discussing How to Upload a Single File in an ASP.NET Core MVC Application with Examples using Buffering and Streaming. Let’s continue with the application we created in our previous article.

Restricting the uploaded file size in ASP.NET Core MVC can be achieved through several methods. Here are the most common approaches:

Using the [RequestSizeLimit] Attribute

You can apply the RequestSizeLimit attribute to an action method to set the maximum allowed size for the request body. This is useful when setting different size limits for different action methods. Suppose our requirement is to upload a file with a maximum size of 1 MB. Then, in that case, we need to decorate the SingleFileUpload action method as follows:

[HttpPost]
[RequestSizeLimit(1000000)] // Limit to 1 MB
public async Task<IActionResult> SingleFileUpload(IFormFile SingleFile)
{
    if (ModelState.IsValid)
    {
        if (SingleFile != null && SingleFile.Length > 0)
        {
            var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads", SingleFile.FileName);

            //Using Buffering
            //using (var stream = System.IO.File.Create(filePath))
            //{
            //    // The file is saved in a buffer before being processed
            //    await SingleFile.CopyToAsync(stream);
            //}

            //Using Streaming
            using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                await SingleFile.CopyToAsync(stream);
            }

            // Process the file here (e.g., save to the database, storage, etc.)
            return View("UploadSuccess");
        }
    }

    return View("Index");
}

Now, run the application and try to upload a file with a size of more than 1 MB, and you will get the following error message.

SPONSOR AD

How do you restrict the uploaded file size in ASP.NET Core MVC?

Setting Limits in Program.cs

You can configure global settings for request limits in the Program.cs class file. This is a good approach if you want to enforce a consistent size limit across the application.

builder.Services.Configure<FormOptions>(options =>
{
    options.MultipartBodyLengthLimit = 1000000; // Limit to 1 MB
});

Now, comment on the RequestSizeLimit attribute, which we applied on the SingleFileUpload action method, and then run the application and upload a file with a size of more than 1 MB. this time, you should get the following error message.

How to Restrict Uploaded File Size in ASP.NET Core MVC

Note: If both settings, i.e., RequestSizeLimit attribute and global size limit in Program.cs class file is present, then the RequestSizeLimit attribute will override the settings placed in the Program.cs class file.

Model Validation

You can validate the file size in your model by checking the file size in the controller action. So, modify the SingleFileUpload action method as follows. Here, we are checking that the file size is not greater than 1 MB.

[HttpPost]
//[RequestSizeLimit(1000000)] // Limit to 1 MB
public async Task<IActionResult> SingleFileUpload(IFormFile SingleFile)
{
    if (SingleFile != null && SingleFile.Length > 1000000) // Limit to 1 MB
    {
        ModelState.AddModelError("", "The file is too large.");
    }

    if (ModelState.IsValid)
    {
        var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads", SingleFile.FileName);

        //Using Buffering
        //using (var stream = System.IO.File.Create(filePath))
        //{
        //    // The file is saved in a buffer before being processed
        //    await SingleFile.CopyToAsync(stream);
        //}

        //Using Streaming
        using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
        {
            await SingleFile.CopyToAsync(stream);
        }

        // Process the file here (e.g., save to the database, storage, etc.)
        return View("UploadSuccess");
    }

    return View("Index");
}

Before running the application to test this, comment on the settings in the Program.cs class and then run the application. Now, upload a file with a size greater than 1 MB, and you should see the following error message.

SPONSOR AD

How to Restrict Uploaded File Size in an ASP.NET Core MVC Application with Examples

Why Restrict Uploaded File Size in an ASP.NET Core MVC?

Restricting the size of uploaded files in an ASP.NET Core MVC application is crucial for several reasons, and it’s a best practice to set appropriate limits based on the application’s requirements. Here are scenarios and reasons why you might want to restrict uploaded file sizes:

  • Server Resource Management: Large files consume significant server resources, including memory and storage. Restricting file size helps in managing these resources more efficiently.
  • Preventing Denial of Service (DoS) Attacks: Allowing large file uploads can make your application vulnerable to DoS attacks, where attackers upload huge files to exhaust server resources, leading to service outages.
  • Improving Performance: Smaller file sizes improve performance, requiring less bandwidth and processing time. This is especially important for applications with a large user base or limited server capacity.
  • User Experience: Restricting file size helps provide a consistent user experience, especially regarding upload times. Users on slower internet connections can struggle with large file uploads.
  • Cost Management: Hosting and bandwidth costs can increase significantly with larger files. Restricting file size can help control these costs.
  • Compliance with Business Rules: Certain applications, like document management systems or profile picture uploads, have specific business requirements for acceptable file sizes.
  • Data Processing Limitations: If the uploaded files are processed (e.g., image resizing, data parsing), there might be limitations on the processing capabilities, necessitating restrictions on file size.

In the next article, I will discuss How to Restrict Uploaded File Types in ASP.NET Core MVC Applications with Examples. In this article, I try to explain How to Restrict Uploaded File Size in ASP.NET Core MVC Applications with Examples. And I hope you enjoy this article.

SPONSOR AD

Leave a Reply

Your email address will not be published. Required fields are marked *