【问题标题】:Form key or value length limit 2048 exceeded表单键或值长度限制 2048 超出
【发布时间】:2017-04-09 09:38:01
【问题描述】:

我正在使用 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);
                    }
                }
            }
.
.

但它不断返回此异常: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
    });

【问题讨论】:

标签: asp.net asp.net-core


【解决方案1】:

默认情况下,ASP.NET Core 在FormReader 中强制执行 2048 的键/值长度限制作为常量并在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
}

因此,您可以使用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));
        }
    }
}

action方法中的使用示例:

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

注意:如果使用的是最新版本的 ASP.NET Core,请将名为 ValueCountLimit 的属性更改为 KeyCountLimit

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

类似问题:

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

Request.Form throws exception

【讨论】:

  • 我为接口成员IOrderedFilter添加了更新,您能确认哪个features名称给出了CS0103错误吗?
  • 它似乎只需要很长时间,没有任何字段名:-并且这两个字段名都不适合我。哪个也好,因为当我们尝试上传时,我仍然会发现它显然将文件大小限制为 2K 的异常? (谁想出了这个疯狂的限制??)
  • 谢谢,[RequestFormLimits(ValueCountLimit = int.MaxValue)] 为我做了 .net core 3.1
【解决方案2】:

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

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

【讨论】:

  • 简单有效。谢谢分享。
【解决方案3】:

这个答案真的很有帮助,谢谢。 但是由于 .Net Core 2.1 有用于此目的的内置属性,例如RequestFormLimitsAttributeRequestSizeLimitAttribute

【讨论】:

    【解决方案4】:
    services.Configure<FormOptions>(options =>
     {
        options.ValueLengthLimit = int.MaxValue;
        options.MultipartBodyLengthLimit = int.MaxValue;
        options.MultipartHeadersLengthLimit = int.MaxValue;
     });
    

    解决了我的问题

    【讨论】:

    • 我还将options.ValueCountLimit = int.MaxValue;添加到此列表+1
    【解决方案5】:

    我在 .Net6 上,这就是我所需要的。 (在我的启动文件里面ConfigureServices(services)。)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-28
      • 1970-01-01
      • 2016-09-13
      • 2022-06-17
      • 1970-01-01
      • 1970-01-01
      • 2020-10-15
      • 1970-01-01
      相关资源
      最近更新 更多