【问题标题】:Read the maxJsonLength from web.config从 web.config 中读取 maxJsonLength
【发布时间】:2014-09-15 20:32:56
【问题描述】:

我需要在运行时从 web.config 中读取 maxJsonLength

  <system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="3000000"/>
      </webServices>
    </scripting>
  </system.web.extensions>
  <system.web>

只需实例化一个新的 JavaScriptSerializer 并读取 MaxJsonLength 属性即可显示默认值 2097152,无论 Web 服务的设置如何。

为什么?

我们有一个 asmx Web 服务,它返回 Json,在极端情况下,返回的数据无法通过内置的序列化程序转换为 Json,我们得到一个丑陋的错误。所有其他异常都会被捕获,并且服务会返回经过清理的自定义异常。

如果我可以读取 maxJsonLength 值并手动尝试在代码中序列化,那么我可以捕获异常并正确处理它。

我不能仅出于此目的在 AppSettings 中复制 maxJsonLength。

是否有任意解析 web.config 以获取此值的通用方法?

【问题讨论】:

    标签: asp.net json web-services web-config


    【解决方案1】:

    请尝试以下代码 sn-p。

    string str = HttpContext.Current.Request.ApplicationPath.ToString();
    Configuration conf = WebConfigurationManager.OpenWebConfiguration(str);
    ScriptingJsonSerializationSection section = (ScriptingJsonSerializationSection)conf.GetSection("system.web.extensions/scripting/webServices/jsonSerialization");
    int Length = section.MaxJsonLength; // Access length here
    

    【讨论】:

    • 行得通!我将不得不缓存该值以避免重复打开每个请求的 web.config 文件。
    • 请在应用程序相关事件中填写。每当您更改此值时,请不要忘记在 IIS 中重新启动您的应用程序。
    • 更新 web.config 将重新启动应用程序池,感谢您的帮助。
    猜你喜欢
    • 2016-08-11
    • 2013-12-29
    • 1970-01-01
    • 2010-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多