超出表格密钥或值长度限制2048

Dot*_*cer 5 asp.net asp.net-core

我使用asp.net核心来构建API.我有一个允许用户使用此代码上传个人资料图片的请求

 [HttpPost("{company_id}/updateLogo")]
        public async Task<IActionResult> updateCompanyLogo(IFormFile imgfile,int company_id)
        {
            string imageName;
            // upload file
            if (imgfile == null || imgfile.Length == 0)
                imageName = "default-logo.jpg";
            else
            {
                imageName = Guid.NewGuid() + imgfile.FileName;
                var path = _hostingEnvironment.WebRootPath + $@"\Imgs\{imageName}";
                if (imgfile.ContentType.ToLower().Contains("image"))
                {
                    using (var fileStream = new FileStream(path, FileMode.Create))
                    {
                        await imgfile.CopyToAsync(fileStream);
                    }
                }
            }
.
.
Run Code Online (Sandbox Code Playgroud)

但它不断返回此异常:Form key or value length limit 2048 exceeded
请求
http://i.imgur.com/25B0qkD.png

更新:
我已经尝试过此代码,但它不起作用

    services.Configure<FormOptions>(options =>
    {
        options.ValueLengthLimit = int.MaxValue; //not recommended value
        options.MultipartBodyLengthLimit = long.MaxValue; //not recommended value
    });
Run Code Online (Sandbox Code Playgroud)

Tet*_*oto 11

默认情况下,ASP.NET Core将内部的键/值长度限制2048强制FormReader为常量并应用,FormOptions如下所示:

public class FormReader : IDisposable
{
    public const int DefaultValueCountLimit = 1024;
    public const int DefaultKeyLengthLimit = 1024 * 2; // 2048
    public const int DefaultValueLengthLimit = 1024 * 1024 * 4; // 4194304
    // other stuff
}

public class FormOptions
{
    // other stuff
    public int ValueCountLimit { get; set; } = DefaultValueCountLimit;
    public int KeyLengthLimit { get; set; } = FormReader.DefaultKeyLengthLimit;
    public int ValueLengthLimit { get; set; } = DefaultValueLengthLimit;
    // other stuff
}
Run Code Online (Sandbox Code Playgroud)

因此,您可以使用KeyValueLimitValueCountLimit属性(也ValueLengthLimit等)创建自定义属性以自行显式设置键/值长度限制:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class RequestSizeLimitAttribute : Attribute, IAuthorizationFilter, IOrderedFilter
{
    private readonly FormOptions _formOptions;

    public RequestSizeLimitAttribute(int valueCountLimit)
    {
        _formOptions = new FormOptions()
        {
            // tip: you can use different arguments to set each properties instead of single argument
            KeyLengthLimit = valueCountLimit,
            ValueCountLimit = valueCountLimit,
            ValueLengthLimit = valueCountLimit

            // uncomment this line below if you want to set multipart body limit too
            // MultipartBodyLengthLimit = valueCountLimit
        };
    }

    public int Order { get; set; }

    // taken from /a/38396065
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var contextFeatures = context.HttpContext.Features;
        var formFeature = contextFeatures.Get<IFormFeature>();

        if (formFeature == null || formFeature.Form == null)
        {
            // Setting length limit when the form request is not yet being read
            contextFeatures.Set<IFormFeature>(new FormFeature(context.HttpContext.Request, _formOptions));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

动作方法中的用法示例:

[HttpPost("{company_id}/updateLogo")]
[RequestSizeLimit(valueCountLimit: 2147483648)] // e.g. 2 GB request limit
public async Task<IActionResult> updateCompanyLogo(IFormFile imgfile, int company_id)
{
    // contents removed for brevity
}
Run Code Online (Sandbox Code Playgroud)

注意:如果使用ASP.NET核心的最新版本,改变属性命名ValueCountLimitKeyCountLimit.

更新:Order属性必须被包含在属性类,因为它是实现接口的成员IOrderedFilter.

类似问题:

表单提交导致"InvalidDataException:超出表单值计数限制1024".

Request.Form抛出异常


nzr*_*tmn 8

对于我的情况,添加[DisableRequestSizeLimit]属性已解决错误;当您不确定请求的最大长度时,这会很有帮助。这是正式文件

    [HttpPost("bulk")]
    [ProducesResponseType(typeof(IEnumerable<Entry>), (int)HttpStatusCode.Created)]
    [ProducesResponseType((int)HttpStatusCode.BadRequest)]
    [ProducesResponseType((int)HttpStatusCode.InternalServerError)]
    [DisableRequestSizeLimit]
    public async Task<IActionResult> BulkCreateEntry([FromBody] IEnumerable<CreateStockEntryFromCommand> command)
    {
        // do your work
    }
Run Code Online (Sandbox Code Playgroud)