How To Resolve Request Body Too Large Error In .Net Core 6

In this article, we are going to learn how to resolve the Request body is too large error while uploading the large video in .Net Core 6.

In my recent project, I want to upload a video, but when I try to upload a video that is less than 30 KB it uploads successfully but when I try to upload exceed than this it gives me an error.

Let’s understand with an example.

Prerequisites

First, open your project, and in that create FileUploadController in the controller folder copy below code.

Here is my API to upload videos in wwwroot folder.

using Microsoft.AspNetCore.Mvc;

namespace UploadLargeFileDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FileUploadController : ControllerBase
    {
        private readonly IWebHostEnvironment _webHostingEnvironment;
        public FileUploadController(IWebHostEnvironment webHostingEnvironment)
        {
            _webHostingEnvironment = webHostingEnvironment;
        }

        [Route("FileUpload")]
        [HttpPost]
        public IActionResult FileUpload(IFormFile files)
        {
            try
            {
                var file = Request.Form.Files[0];
                var webRootPath = _webHostingEnvironment.WebRootPath;
                var newPath = Path.Combine(webRootPath, "FileUpload");
                if (!Directory.Exists(newPath)) Directory.CreateDirectory(newPath);
                if (file.Length > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var fullPath = Path.Combine(newPath, fileName);
                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                    }
                }
                return Ok("Upload Successful.");
            }
            catch (Exception ex)
            {
                return BadRequest("Upload Failed: " + ex.Message);
            }
        }
    }
}

Let’s see the output.

As you can see in the above video when I try to upload a video whose size is 26 KB is uploaded successfully but when I try to upload a video whose size is 136 KB it throws an error.

Not to worry just add the following lines in your program.cs and this error resolved.

using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core;

var builder = WebApplication.CreateBuilder(args);
//IIS
builder.Services.Configure<IISServerOptions>(options =>
{
    options.MaxRequestBodySize = int.MaxValue;
});
//Kestrel
builder.Services.Configure<KestrelServerOptions>(options =>
{
    options.Limits.MaxRequestBodySize = int.MaxValue;
});
builder.Services.Configure<FormOptions>(options =>
{
    options.ValueLengthLimit = int.MaxValue;
    options.MultipartBodyLengthLimit = int.MaxValue;
    options.MultipartHeadersLengthLimit = int.MaxValue;
});
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

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

app.UseAuthorization();

app.MapControllers();

app.Run();

When the applications running on the IIS server you have to add the below code:

services.Configure<IISServerOptions>(options =>
{
    options.MaxRequestBodySize = int.MaxValue;
});

When the application running on Kestrel you have to add below code:

services.Configure<KestrelServerOptions>(options =>
{
    options.Limits.MaxRequestBodySize = int.MaxValue;
});

Form’s MultipartBodyLengthLimit:

services.Configure<FormOptions>(options =>
{
    options.ValueLengthLimit = int.MaxValue;
    options.MultipartBodyLengthLimit = int.MaxValue; // if don't set default value is: 128 MB
    options.MultipartHeadersLengthLimit = int.MaxValue;
});

That’s it.

Now you can see that the same API allows us to upload video whose size is 136 KB.

Also check, Send Mail Using OAuth 2.0 In .Net Core 6.0 Part 1

Submit a Comment

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

Subscribe

Select Categories