2016-07-13 28 views
9

我創建了一個mvc網站,並且我發佈了大量的json表單數據(Content-Type:application/x-www-form-urlencoded) 回到mvc控制器。當我這樣做時,我收到一個500響應,指出:「InvalidDataException:表單值計數限制1024超出。」表單提交導致「InvalidDataException:超出表單值計數限制1024」。

在ASPNET的早期版本中,您將在下面添加到web.config中增加限制:

<appSettings> 
    <add key="aspnet:MaxHttpCollectionKeys" value="5000" /> 
    <add key="aspnet:MaxJsonDeserializerMembers" value="5000" /> 
</appSettings> 

當我把這些值在web.config中,我看不出有什麼變化,所以我猜測微軟不再從web.config中讀取這些值。 但是,我無法弄清楚這些設置應該設置在哪裏。

任何幫助增加表單值計數非常感謝!

需要明確的是,這要求工作完全正常的時候在我的崗位數據項的數量少於1024

+1

你是什麼意思「大量的json形式的數據」?你是否將數據發佈爲'application/x-www-form-urlencoded'內容類型或'application/json'? –

+0

@KiranChalla我正在使用內容類型:應用程序/ x-www-form-urlencoded –

回答

11

您可以使用FormOptions更改默認formvalue限制。如果您使用的是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) 

注意:如果你的動作需要支持防僞驗證過,那麼你就需要訂購的過濾器。例如:

// 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) 
+0

這工作就像一個魅力。非常感謝! –

+0

上面的代碼解決了這個問題,但我認爲新MVC內核中的變量名已經有更新。 「ValueCountLimit」現在是「」KeyCountLimit「變量 我發現上述代碼的修正變量名稱與新版本的相同類型http://stepbystepschools.net/?p=1044 –

+1

它已經在新版本的在asp.net核心,請參閱提交:https://github.com/aspnet/Mvc/commit/17f6b17a6dc0e76606b091187a4e43a184656c89 –