Dejan Dimčić
Dejan Dimčić

Reputation: 294

Request.Form throws exception

I am making ASP.NET Core web application, and I am uploading PDF file through HttpContext from javascript file. So, when I am trying to load file on the server side, using Request.Form.File, Form is throwing exception of type System.IO.InvalidDataException. Form message is saying: "Multipart body length limit 16384 exceeded". I tried to edit web.config file in order to increase that limit, but message is always the same. Is there anything I am missing or I am looking on the wrong side?

Thanks.

Upvotes: 3

Views: 4918

Answers (1)

akardon
akardon

Reputation: 45966

Define this attribute :

[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));
        }
    }
}

And add this attribute to your action method see what happens:

[RequestFormSizeLimit(valueCountLimit: 2147483648)]
[HttpPost]
public IActionResult ActionMethod(...)
{
  ...
}

Upvotes: 3

Related Questions