我创建了一个mvc网站,我发布了大量的json表单数据(Content-Type:application/x-www-form-urlencoded
)
回到mvc控制器。当我这样做时,我收到500响应,声明:“InvalidDataException:超出表单值计数限制1024。”
在以前版本的aspnet中,您可以将以下内容添加到web.config中以增加限制:
<appSettings>
<add key="aspnet:MaxHttpCollectionKeys" value="5000" />
<add key="aspnet:MaxJsonDeserializerMembers" value="5000" />
</appSettings>
当我将这些值放在web.config中时,我没有看到任何更改,因此我猜测Microsoft不再从web.config中读取这些值。 但是,我无法弄清楚应该在哪里设置这些设置。
非常感谢任何有关增加表单值计数的帮助!
要明确的是,当我的帖子数据中的项目数量少于1024时,此请求可以正常运行。
答案 0 :(得分:24)
默认 formvalue(非formkey)限制为1024.
此外,我认为您只需更改 Startup.cs 文件中的FormOptions
限制。
public void ConfigureServices(IServiceCollection services)
{
services.Configure<FormOptions>(options =>
{
options.ValueCountLimit = int.MaxValue;
});
}
答案 1 :(得分:16)
更新:MVC SDK现在通过RequestSizeLimitAttribute
包含此功能。不再需要创建自定义属性。
感谢andrey-bobrov将其指向comment。对于子孙后代,原来的答案如下。
您可以使用FormOptions
更改默认的表格值限制。如果您正在使用MVC,那么您可以创建一个过滤器并装饰您希望扩展此限制的操作,并保留其余操作的默认值。
/// <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));
}
}
}
<强>动作强>:
[HttpPost]
[RequestFormSizeLimit(valueCountLimit: 2000)]
public IActionResult ActionSpecificLimits(YourModel model)
注意:如果您的操作也需要支持Antiforgery验证,那么您需要订购过滤器。例如:
// 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)
答案 2 :(得分:6)
就我而言,它是通过更改Startup.cs文件中的ValueLengthLimit来工作的
any
答案 3 :(得分:2)
使用 .net core 3.1,您还需要
services.Configure<FormOptions>(options =>
{
options.ValueCountLimit = int.MaxValue;
});
还有
services.AddMvc(options =>
{
options.MaxModelBindingCollectionSize = int.MaxValue;
});
在这里找到:https://stackoverflow.com/a/64500089/14958019
仅使用 MaxModelBindingCollectionSize 我得到的 json 对象超过 1024 行,完全从带有 ajax 的 javascript 传递到 mvc 控制器。
答案 4 :(得分:0)
如果您使用的是.net core 2.1或更高版本,则可以在控制器或操作上使用如下所示的内置RequestFormLimits属性
[RequestFormLimits(ValueCountLimit = 5000)]
public class TestController: Controller
答案 5 :(得分:0)