2013-12-11 38 views
5

我有一個MVC3應用程序在.NET 4.0下運行,當我使用JavascriptSerializer.Deserialize時出現錯誤。Web.config jsonSerialization maxJsonLength ignored

使用JSON JavaScriptSerializer進行序列化或反序列化時出錯。字符串的長度超過maxJsonLength屬性中設置的值。

閱讀Can I set an unlimited length for maxJsonLength in web.config我把jsonSerialization maxJsonLength鍵放在我的web.config中,但它被忽略。雖然我可以在代碼中設置JavaScriptSerializer.MaxJsonLength屬性,但它工作正常。

我想要在Web.config而不是代碼中的值。這是我如何使用JavaScriptSerializer

Dim client As New WebClient 
... 
Dim result = _client.DownloadString("Test") 
Dim serializer = New JavaScriptSerializer 
Return serializer.Deserialize(Of Foo)(result) 

這是我Web.config

<configuration> 
    <configSections> 
    ... 
    </configSections> 
    <appSettings> 
    ... 
    </appSettings> 
    <system.web> 
    <customErrors mode="On"> 
     <error statusCode="404" redirect="/Http404"/> 
     <error statusCode="403" redirect="/Http403"/> 
     <error statusCode="550" redirect="/Http550"/> 
    </customErrors> 
    <compilation debug="true" targetFramework="4.0"/> 
    <pages controlRenderingCompatibilityVersion="4.0"> 
     <namespaces> 
     <add namespace="System.Web.Helpers"/> 
     <add namespace="System.Web.Mvc"/> 
     <add namespace="System.Web.Mvc.Ajax"/> 
     <add namespace="System.Web.Mvc.Html"/> 
     <add namespace="System.Web.Routing"/> 
     <add namespace="System.Web.WebPages"/> 
     </namespaces> 
    </pages> 
    </system.web> 
    <system.web.extensions> 
    <scripting> 
     <webServices> 
     <jsonSerialization maxJsonLength="50000000"/> 
     </webServices> 
    </scripting> 
    </system.web.extensions> 
<system.webServer> 
.... 
</system.webServer> 
</configuration> 

回答

10

根據您提供的鏈接(2最投票的答案),你的web.config設置會因爲你使用的是內部實例被忽略的JavaScriptSerializer

如果你需要存儲在web.config中的值,你可以在<appSettings>部分添加一鍵叫maxJsonLength50000000一個值,然後在你的代碼,你可以使用它像:

var serializer = new JavaScriptSerializer(); 
serializer.MaxJsonLength = ConfigurationManager.AppSettings['maxJsonLength']; 
+1

你應該加粗**內部實例**。這就是我誤解! –

+0

完成。也只是意識到我給你一個C#的例子,直到現在沒有看到你的vb.net標籤:) – lhan