简体   繁体   中英

How to handle form error of Form value length limit exceeded in asp.net core 5

In my case, I am working on ASP.NET Core 5 project and I need to limit the maximum size for the entire form content to 2MB.

I have added the following attribute to my controller

[RequestFormLimits(ValueLengthLimit = 1024 * 1024 * 2)]
public class MyController : Controller
{
  ...
}

but the problem is that anytime a user tries to upload an image or any other form item that makes the entire content of the form to be more than 2MB, the application returns a 404 error.

I am looking for a way to rather display an error message when the entire content of the form exceeds 2MB.

I will appreciate any guide to handle this error gracefully instead of the 404 error it currently displays to users

Thank you

On the client side you can do something similar to this to check for file size:

$("input[type='file']").on("change", function () {
    if (this.files[0].size > 2000000000) {
        alert("Please upload a file less than 2GB.");
        $(this).val('');
    }
   }

On the server side you can have a property IFormFile and check the size. file.FormFile.Length > 5 * 1024 * 1024;

Or you can create a custom Validation Attribute which I prefer. This should help you get started. https://stackoverflow.com/a/56592790/9936356

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM