Restrict Uploaded File Size in ASP.NET Core

Introduction

In ASP.NET Core, you can restrict the uploaded file size using the RequestSizeLimit attribute in the Program.cs file or by configuring it in the appsettings.json file. Additionally, you can set the maximum file size programmatically in your controller actions.

Why do we need to restrict uploaded File Size in an ASP.NET Core?

  1. Preventing Denial of Service (DoS) Attacks: Allowing unrestricted file uploads can open your application to DoS attacks where malicious users upload excessively large files, consuming server resources and potentially crashing the application or degrading its performance. Limiting file sizes helps mitigate this risk by preventing excessively large uploads.
  2. Optimizing Server Resources: Large file uploads consume server resources such as memory and disk space. By restricting file sizes, you can better manage these resources, ensuring that your application remains responsive and efficient, especially in shared hosting environments where resource allocation may be limited.
  3. Ensuring Application Stability: Processing large files can strain server resources and lead to performance issues, timeouts, or crashes. Limiting file sizes helps maintain the stability and reliability of your application by preventing excessive resource consumption during file uploads.
  4. Improving User Experience: Uploading large files can be time-consuming, especially for users with slow internet connections. Limiting file sizes encourages users to upload smaller, more manageable files, resulting in a faster and smoother user experience.
  5. Compliance and Regulation: In some cases, regulatory requirements or best practices may dictate maximum file sizes for security or operational reasons. Enforcing file size restrictions helps ensure compliance with such standards and demonstrates a commitment to security and data management practices.

1. Using RequestSizeLimit Attribute

You can use the RequestSizeLimit attribute to restrict the maximum size of the request body, which includes uploaded files.

builder.Services.Configure<FormOptions>(options =>
{
    options.ValueCountLimit = int.MaxValue;
    options.KeyLengthLimit = int.MaxValue;
    options.ValueLengthLimit = int.MaxValue;
    options.MultipartBodyLengthLimit = 1000000; // Limit to 1 MB

});

This configuration sets the maximum size of the multipart body to 50 MB.

2. Using appsettings.json

Alternatively, you can configure the maximum request size in the appsettings.json file:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "FormOptions": {
    "MultipartBodyLengthLimit": 1000000
  }
}

This configuration sets the maximum size of the multipart body to 50 MB.

3. Programmatically in Controller Action

You can also set the maximum file size programmatically in your controller action using the RequestSizeLimit attribute:

Add a controller

  1. In Solution Explorer, right-click Controllers > Add > Controller.
  2. In the Add New Scaffolded Item dialog box, select MVC Controller - Empty > Add.
  3. In the Add New Item - RestrictUploadedFileSize_Demo dialog, enter FileUploadController.cs and select Add.

Replace the contents of Controllers/ FileUploadController.cs with the following code.

using Microsoft.AspNetCore.Mvc;

namespace RestrictUploadedFileSize_Demo.Controllers
{
    public class FileUploadController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

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

                    //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");
        }
    }
}

This configuration applies only to the specific controller action.

Choose the approach that best fits your requirements and implementation style. Make sure to handle the error gracefully and inform the client about the file size limit to avoid confusion.

Add a view

  1. Right-click on the Views folder, then Add > New Folder and name the folder Companies
  2. Right-click on the Views/ FileUpload folder, and then Add > New Item.
  3. In the Add New Item dialog, select Show All Templates.
  4. In the Add New Item - RestrictUploadedFileSize_Demo dialog:
  5. In the search box in the upper-right, enter the view
  6. Select Razor View - Empty
  7. Keep the Name box value, Index.cshtml.
  8. Select Add
  9. Replace the contents of the Views/FileUpload/Index.cshtml Razor view file with the following:

Index.cshtml

@{
    ViewData["Title"] = "Index";
}

<h2>File Upload</h2>
<hr />
<div class="row">
    <div class="col-md-12">
        <form method="post" asp-controller="FileUpload" asp-action="FileUpload"enctype="multipart/form-data">
            <div asp-validation-summary="All" class="text-danger"></div>
            <input type="file" name="SingleFile" class="form-control" />
            <button type="submit" name="Upload" class="btn btn-primary">Upload</button>
        </form>
    </div>
</div>

Run the Application

Select Ctrl+F5 to run the app without the debugger. Visual Studio runs the ASP.NET app and opens the default browser.

File upload

Single file upload

Conclusion

By restricting uploaded file sizes in ASP.NET Core, you can enhance the security, stability, and performance of your application while providing a better user experience and ensuring compliance with regulatory requirements. It's an important aspect of building robust and reliable web applications.