InvalidDataException: Form key or value length limit 2048 exceeded :- ASP.NET MVC core.

One of our students got the following error while making a huge post to the ASP.NET MVC core WebAPI. So the error is very clear, ASP.NET does not allow to post you data which have value and key length above 2048 and if you want to do it then you need to explicitly enable the same.

response

For the same we wrote a simple filter as shown below , which allows post of huge data.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
publicclassRequestFormSizeLimitAttribute : Attribute, IAuthorizationFilter, IOrderedFilter
    {
privatereadonlyFormOptions _formOptions;

publicRequestFormSizeLimitAttribute(intvalueCountLimit)
        {
            _formOptions = newFormOptions()
            {

KeyCountLimit = valueCountLimit,
KeyLengthLimit = valueCountLimit
            };
        }

publicint Order { get; set; }

publicvoidOnAuthorization(AuthorizationFilterContext context)
        {
var features = context.HttpContext.Features;
varformFeature = features.Get();

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

Once you have written this attribute you can decorate on the WebAPI on which you want the post to happen as shown in the below code.

[RequestFormSizeLimit(valueCountLimit: 10000, Order = 1)]
 [Route("api/[controller]")]
publicclassPatientController : Controller
 {}

Do not miss our next ASP.NET MVC batch coming week in Mumbai
http://stepbystepschools.net/?page_id=315

Comments

comments

This entry was posted in ASP.NET MVC Training, Class Room Training, MVC, MVC Training in Mumbai and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.