0

I'm trying to create an ASP.NET Core MVC application that allows uploading files up to a fixed size and saving them on a dedicated physical location.

When I upload any file of a few megabytes (png images, jpg or other file types such as mp3 etc...), everything works correctly; however, when I try to upload a video of 80 megabytes, I get an error:

System.NullReferenceException: Object reference not set to an instance of an object.

postedFiles was null.

TeachingController:

using Microsoft.AspNetCore.Mvc;

namespace VideoKnowledge.Controllers
{
    public class TeachingController : Controller
    {
        private IWebHostEnvironment Environment;

        public TeachingController(IWebHostEnvironment _environment)
        {
            Environment = _environment;
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [RequestFormLimits(MultipartBodyLengthLimit = 104857600)]
        public IActionResult Index(List<IFormFile> postedFiles)
        {
            string wwwPath = this.Environment.WebRootPath;
            string contentPath = this.Environment.ContentRootPath;

            string path = Path.Combine(this.Environment.WebRootPath, "Uploads");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            List<string> uploadedFiles = new List<string>();

            foreach (IFormFile postedFile in postedFiles)
            {
                string fileName = Path.GetFileName(postedFile.FileName);

                using (FileStream stream = new FileStream(Path.Combine(path, fileName), FileMode.Create))
                {
                    postedFile.CopyTo(stream);
                    uploadedFiles.Add(fileName);
                    ViewBag.Message += string.Format("<b>{0}</b> uploaded.<br />", fileName);
                }
            }

            return View();
        }
    }
}

Views/Teaching/Index.cshtml:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }
    </style>
</head>
<body>
    <form method="post" enctype="multipart/form-data" asp-controller="Teaching" asp-action="Index">

        <span>Select File:</span>
        <input type="file" name="postedFiles" multiple />
        <input type="submit" value="Upload" />
        <br />
        <span style="color:green">@Html.Raw(ViewBag.Message)</span>
    </form>

</body>
</html>

web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.webServer>
        <security>
            <requestFiltering>
                <requestLimits maxAllowedContentLength="204857600" />
            </requestFiltering>
        </security>
    </system.webServer>
</configuration>

program.cs:

using Microsoft.AspNetCore;
using VideoKnowledge;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddRazorPages();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.MapRazorPages();

app.Run();

Could someone help me figure out what I'm doing wrong? The end result should be to load the video and show in the Teaching/index.cshtml view a list of videos loaded like this (I have yet to write this).

Thanks in advance for your attention.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Marco
  • 9
  • 2
  • Check also https://stackoverflow.com/questions/3853767/maximum-request-length-exceeded/ – Steve Aug 05 '23 at 17:15
  • I tried to change the web.config file like this but the error is still the same. thank for your reply! web.config: – Marco Aug 05 '23 at 17:38
  • I have code like this and works. The only difference I can see is the fact that I use a Model and the BindProperty attribute on the model instance. Inside the model a property for IPostedFile transfers correctly the info to the cs code behind – Steve Aug 05 '23 at 17:55
  • Maybe you don't have enough disk space where the request is temporarily saved? – Nikolay Aug 05 '23 at 21:50
  • See this link on uploading files bigger than 30 MB. https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-7.0. You might need to set the Kestrel maximum request body size to a higher value. – SoftwareDveloper Aug 06 '23 at 17:48

1 Answers1

0

By default ASP.NET Core has a maximum request size limit of 30 Mb for files. In addition to the file size request decoration you have labelled the controller with, you can add this code to configure the service running the web app to allow file sizes greater than 30 Mega Bytes like in the code below

services.Configure<IISServerOptions>(options =>
{
    // Set the maximum request size (100 MB in this example)
    options.MaxRequestBodySize = 104857600; 
});
Son of Man
  • 1,213
  • 2
  • 7
  • 27