Form submit resulting in "InvalidDataException: Form value count limit 1024 exceeded."
Asked Answered
I

7

55

I have created an mvc site and I'm posting a large amount of json form data (Content-Type:application/x-www-form-urlencoded) back to the mvc controller. When I do this, I receive a 500 response that states: "InvalidDataException: Form value count limit 1024 exceeded."

In previous versions of aspnet, you would add the following to the web.config to increase the limit:

<appSettings>
    <add key="aspnet:MaxHttpCollectionKeys" value="5000" />
    <add key="aspnet:MaxJsonDeserializerMembers" value="5000" />
</appSettings>

When I put these values in the web.config, I do not see any change, so I'm guessing Microsoft is no longer reading these values out of the web.config. However, I cannot figure out where these settings should be set.

Any help with increasing the form value count is greatly appreciated!

To be clear, this request works perfectly fine when the number of items in my post data is less than 1024.

Update: In asp.net MVC Core 3.1 the error message is - "Failed to read the request form. Form value count limit 1024 exceeded."

Intercellular answered 13/7, 2016 at 16:28 Comment(2)
What do you mean by large amount of json form data? Are you posting data as application/x-www-form-urlencoded content type or application/json?Banka
@KiranChalla I am using Content-Type:application/x-www-form-urlencodedIntercellular
B
27

Update: The MVC SDK now includes this functionality via RequestSizeLimitAttribute. There is no longer any need to create a custom attribute.

Thanks to andrey-bobrov for pointing this out in a comment. The original answer is below, for posterity.


You can change the default formvalue limit using the FormOptions. If you are using MVC, then you can create a filter and decorate on action where you want to extend this limit and keep the default for rest of the actions.

/// <summary>
/// Filter to set size limits for request form data
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class RequestFormSizeLimitAttribute : Attribute, IAuthorizationFilter, IOrderedFilter
{
    private readonly FormOptions _formOptions;

    public RequestFormSizeLimitAttribute(int valueCountLimit)
    {
        _formOptions = new FormOptions()
        {
            ValueCountLimit = valueCountLimit
        };
    }

    public int Order { get; set; }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var features = context.HttpContext.Features;
        var formFeature = features.Get<IFormFeature>();

        if (formFeature == null || formFeature.Form == null)
        {
            // Request form has not been read yet, so set the limits
            features.Set<IFormFeature>(new FormFeature(context.HttpContext.Request, _formOptions));
        }
    }
}

Action:

[HttpPost]
[RequestFormSizeLimit(valueCountLimit: 2000)]
public IActionResult ActionSpecificLimits(YourModel model)

NOTE: If your action needs to support Antiforgery validation too, then you would need to order the filters. Example:

// Set the request form size limits *before* the antiforgery token validation filter is executed so that the
// limits are honored when the antiforgery validation filter tries to read the form. These form size limits
// only apply to this action.
[HttpPost]
[RequestFormSizeLimit(valueCountLimit: 2000, Order = 1)]
[ValidateAntiForgeryToken(Order = 2)]
public IActionResult ActionSpecificLimits(YourModel model)
Banka answered 13/7, 2016 at 19:24 Comment(7)
The above code solves the problem but i think there has been updates in variable names in the new MVC core. "ValueCountLimit " is now ""KeyCountLimit " variable. I found the same type of above code with corrected variable names with new version stepbystepschools.net/?p=1044Beginning
it has been implemented already in the new version of the asp.net core, see commit: github.com/aspnet/Mvc/commit/…Zebec
@AndreyBobrov is this safe to increase? This is in relation to learn.microsoft.com/en-us/security-updates/securitybulletins/… where increase post size increases chance of exploitation.Tera
Creating a custom attribute like RequestFormSizeLimit works for sure, but wondering what limit should be used?. If there is a form where you can add input controls dynamically and make a post call to save them, this limit keeps increasing. So does anyone know what is the max or should I say safer limit would be(for .net core 2.0 and Angular7 SPA site)? Thanks!Priddy
is the attribute RequestSizeLimitAttribute not available in ASP.NET Core 1.1?Electorate
Also for .Net Core ASP you need services.Configure<FormOptions>(options => { options.MemoryBufferThreshold = 1500000000; options.MultipartBodyLengthLimit = 1500000000; }); in your Startup.csSulphanilamide
Works for Asp.net Core 3.1 as it isHerstein
B
93

The default formvalue(not formkey) limit is 1024.

Also, I think you can just change the FormOptions limit in Startup.cs file.

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<FormOptions>(options =>
    {
        options.ValueCountLimit = int.MaxValue;
    });
}
Bim answered 28/4, 2018 at 14:54 Comment(3)
This worked perfect for me using asp.core. Found it in the startup.cs file and changed it to services.Configure<FormOptions>(x => x.ValueCountLimit = 8192);Channing
This is a good answer as its globally set, rather than individual method.Astrophysics
This just prevented me from rewriting a bunch of code. Thank you! Was looking for 2 hours trying to find out what was going on. I knew the size of the request wasn't too big but something was not letting it go though. Thanks again.Safeconduct
P
35

If you are using .net core 2.1 or above, you can use the built in RequestFormLimits attribute as shown below on a controller or action-

[RequestFormLimits(ValueCountLimit = 5000)]
public class TestController: Controller

Link to official docs

Priddy answered 2/4, 2019 at 15:27 Comment(3)
Doesn't seem to work in .NET 5 and up.Vole
@NielsVanhorenbeeck You found any solution for .net 5 ?Selfabasement
@KhantHtetNaing, yes put the following in the StartUp where you configure services services.Configure<FormOptions>(options => { options.ValueCountLimit = 5000; });Vole
B
27

Update: The MVC SDK now includes this functionality via RequestSizeLimitAttribute. There is no longer any need to create a custom attribute.

Thanks to andrey-bobrov for pointing this out in a comment. The original answer is below, for posterity.


You can change the default formvalue limit using the FormOptions. If you are using MVC, then you can create a filter and decorate on action where you want to extend this limit and keep the default for rest of the actions.

/// <summary>
/// Filter to set size limits for request form data
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class RequestFormSizeLimitAttribute : Attribute, IAuthorizationFilter, IOrderedFilter
{
    private readonly FormOptions _formOptions;

    public RequestFormSizeLimitAttribute(int valueCountLimit)
    {
        _formOptions = new FormOptions()
        {
            ValueCountLimit = valueCountLimit
        };
    }

    public int Order { get; set; }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var features = context.HttpContext.Features;
        var formFeature = features.Get<IFormFeature>();

        if (formFeature == null || formFeature.Form == null)
        {
            // Request form has not been read yet, so set the limits
            features.Set<IFormFeature>(new FormFeature(context.HttpContext.Request, _formOptions));
        }
    }
}

Action:

[HttpPost]
[RequestFormSizeLimit(valueCountLimit: 2000)]
public IActionResult ActionSpecificLimits(YourModel model)

NOTE: If your action needs to support Antiforgery validation too, then you would need to order the filters. Example:

// Set the request form size limits *before* the antiforgery token validation filter is executed so that the
// limits are honored when the antiforgery validation filter tries to read the form. These form size limits
// only apply to this action.
[HttpPost]
[RequestFormSizeLimit(valueCountLimit: 2000, Order = 1)]
[ValidateAntiForgeryToken(Order = 2)]
public IActionResult ActionSpecificLimits(YourModel model)
Banka answered 13/7, 2016 at 19:24 Comment(7)
The above code solves the problem but i think there has been updates in variable names in the new MVC core. "ValueCountLimit " is now ""KeyCountLimit " variable. I found the same type of above code with corrected variable names with new version stepbystepschools.net/?p=1044Beginning
it has been implemented already in the new version of the asp.net core, see commit: github.com/aspnet/Mvc/commit/…Zebec
@AndreyBobrov is this safe to increase? This is in relation to learn.microsoft.com/en-us/security-updates/securitybulletins/… where increase post size increases chance of exploitation.Tera
Creating a custom attribute like RequestFormSizeLimit works for sure, but wondering what limit should be used?. If there is a form where you can add input controls dynamically and make a post call to save them, this limit keeps increasing. So does anyone know what is the max or should I say safer limit would be(for .net core 2.0 and Angular7 SPA site)? Thanks!Priddy
is the attribute RequestSizeLimitAttribute not available in ASP.NET Core 1.1?Electorate
Also for .Net Core ASP you need services.Configure<FormOptions>(options => { options.MemoryBufferThreshold = 1500000000; options.MultipartBodyLengthLimit = 1500000000; }); in your Startup.csSulphanilamide
Works for Asp.net Core 3.1 as it isHerstein
E
23

In my case, it worked by changing ValueLengthLimit, in Startup.cs file

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<FormOptions>(options =>
    {
        options.ValueCountLimit = 200; // 200 items max
        options.ValueLengthLimit = 1024 * 1024 * 100; // 100MB max len form data
    });
Edile answered 28/9, 2018 at 21:7 Comment(1)
This worked just fine for me in Dotnet Core 2.1! Many thanks :-)Docker
E
12

With .net core 3.1 you need in addition to

services.Configure<FormOptions>(options =>
{
    options.ValueCountLimit = int.MaxValue;
});

also

services.AddMvc(options =>
{
    options.MaxModelBindingCollectionSize = int.MaxValue;
});

Found here: https://mcmap.net/q/912399/-collection-bound-to-39-model-39-exceeded-mvcoptions-maxmodelbindingcollectionsize-1024

Only with MaxModelBindingCollectionSize i get my json object with more than 1024 rows fully passed from javascript with ajax to mvc controller.

Equivocation answered 7/1, 2021 at 10:46 Comment(1)
Still working for .net core 8Commensurate
C
3

Form value count limit is basically total no. of parameters you passed in request.

Limit can be set from Startup.cs:

 services.Configure<FormOptions>(options =>
            {
                options.ValueCountLimit = 199;
            });

See image below, I have passed 200 parameters in a request. Default limit is 1024 but I have set it as 199 so I pass more than 199 parameters then It will gives an error.

enter image description here

enter image description here

Cartomancy answered 21/4, 2021 at 11:59 Comment(0)
C
0

The default limit on the amount of allowed form entries is controlled by the ValueCountLimit property of FormOptions. You can use the options pattern to configure the value.

For example:

builder.Services.Configure<FormOptions>(configuration.GetSection("Form"));

You can then define a configuration section to define a new value:

"Form": {
    "ValueCountLimit": 2048
  }

This provides a more flexible approach than hard-coding the values. You should avoid setting an arbitrarily high value as the limit will help to prevent against denial of service attacks caused by submitting extremely large forms.

Other properties of FormOptions can be set using the same method. Omitted values will use the defaults.

Callboy answered 12/4, 2022 at 8:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.