asp.net - unlimited - maxjsonlength iis
web.configのmaxJsonLengthに無制限の長さを設定できますか? (18)
私はjQueryのオートコンプリート機能を使用しています。 17000以上のレコードのリストを取得しようとすると(長さが10文字を超えない)、長さを超えてエラーがスローされます。
例外情報:
例外の種類:InvalidOperationException
例外メッセージ:JSON JavaScriptSerializerを使用してシリアライズまたはデシリアライズ中にエラーが発生しました。 文字列の長さがmaxJsonLengthプロパティで設定された値を超えています。
web.config
maxJsonLength
に無制限の長さを設定できますか? そうでない場合は、私が設定できる最大の長さは何ですか?
MVC 4では次のことができます。
protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonResult()
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior,
MaxJsonLength = Int32.MaxValue
};
}
あなたのコントローラーで。
添加:
あなたが指定する必要があるパラメータに戸惑う人にとっては、呼び出しは次のようになります。
Json(
new {
field1 = true,
field2 = "value"
},
"application/json",
Encoding.UTF8,
JsonRequestBehavior.AllowGet
);
MVC 4を使用している場合は、 この回答も確認してください。
それでもエラーが表示される場合:
-
maxJsonLength
プロパティをweb.configの最大値に設定した後 - あなたのデータの長さがこの値よりも小さいことがわかっている
- JavaScriptのシリアル化にWebサービスメソッドを利用していない
あなたの問題はそうである可能性が高いです:
MaxJsonLengthプロパティの値は、Webサービスメソッドを呼び出すために非同期通信レイヤーで使用される内部JavaScriptSerializerインスタンスにのみ適用されます。 ( MSDN:ScriptingJsonSerializationSection.MaxJsonLengthプロパティ )
基本的に、 "internal" JavaScriptSerializer
は、Webメソッドから呼び出されたときにmaxJsonLength
の値を尊重します。 JavaScriptSerializer
直接使用する(またはMVCアクションメソッド/コントローラ経由で使用する)場合、少なくともweb.configのsystemWebExtensions.scripting.webServices.jsonSerialization
セクションからmaxJsonLength
プロパティをmaxJsonLength
ません 。
回避策として、コントローラ内で(または実際にはどこでも)以下を実行できます。
var serializer = new JavaScriptSerializer();
// For simplicity just use Int32's max value.
// You could always read the value from the config section mentioned above.
serializer.MaxJsonLength = Int32.MaxValue;
var resultData = new { Value = "foo", Text = "var" };
var result = new ContentResult{
Content = serializer.Serialize(resultData),
ContentType = "application/json"
};
return result;
この答えは、 このasp.netフォーラムの答えの私の解釈です。
Viewでこのような問題が発生した場合は、以下の方法を使用して問題を解決できます。 ここでIused Newtonsoftパッケージ。
@using Newtonsoft.Json
<script type="text/javascript">
var partData = @Html.Raw(JsonConvert.SerializeObject(ViewBag.Part));
</script>
WebForms UpdatePanelのソリューション:
Web.configに設定を追加する:
<configuration>
<appSettings>
<add key="aspnet:UpdatePanelMaxScriptLength" value="2147483647" />
</appSettings>
</configuration>
https://support.microsoft.com/en-us/kb/981884
ScriptRegistrationManager
クラスには次のコードが含まれています:
// Serialize the attributes to JSON and write them out
JavaScriptSerializer serializer = new JavaScriptSerializer();
// Dev10# 877767 - Allow configurable UpdatePanel script block length
// The default is JavaScriptSerializer.DefaultMaxJsonLength
if (AppSettings.UpdatePanelMaxScriptLength > 0) {
serializer.MaxJsonLength = AppSettings.UpdatePanelMaxScriptLength;
}
string attrText = serializer.Serialize(attrs);
web.configファイルでjson要求の最大長を設定できます:
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="....">
</jsonSerialization>
</webServices>
</scripting>
</system.web.extensions>
</configuration>
maxJsonLengthのデフォルト値は102400です。 詳細については、次のMSDNページを参照してください。http: http://msdn.microsoft.com/en-us/library/bb763183.aspx
「無制限」の価値はないようです。 デフォルトは2097152文字です。これは4 MBのUnicode文字列データに相当します。
既に観察されているように、17,000レコードはブラウザでうまく使えません。 集約ビューを表示している場合は、サーバー上で集計を行い、ブラウザーで集計のみを転送する方がはるかに効率的です。 たとえば、ファイルシステムのブラウザーを考えてみましょう。ツリーの上部が表示された後、ドリルダウンしてさらに要求を出します。 各要求で返されるレコードの数は比較的少ない。 ツリービューのプレゼンテーションは、大きな結果セットに対してうまく機能します。
代替ASP.NET MVC 5修正:
(私の場合は上記のMFCの回答に似ていますが、いくつかの小さな変更があります)
私はまだJson.NETに変更する準備ができていませんでしたが、私の場合はリクエスト中にエラーが発生していました。 私のシナリオでは、グローバルプロジェクトに修正プログラムを適用する実際のJsonValueProviderFactory
を変更し、 global.cs
ファイルをそのように編集することで可能になりました。
JsonValueProviderConfig.Config(ValueProviderFactories.Factories);
web.configエントリを追加します。
<add key="aspnet:MaxJsonLength" value="20971520" />
次の2つのクラスを作成します
public class JsonValueProviderConfig
{
public static void Config(ValueProviderFactoryCollection factories)
{
var jsonProviderFactory = factories.OfType<JsonValueProviderFactory>().Single();
factories.Remove(jsonProviderFactory);
factories.Add(new CustomJsonValueProviderFactory());
}
}
これは、基本的にSystem.Web.Mvc
にあるデフォルト実装の正確なコピーですが、設定可能なweb.config appsetting値aspnet:MaxJsonLength
ます。
public class CustomJsonValueProviderFactory : ValueProviderFactory
{
/// <summary>Returns a JSON value-provider object for the specified controller context.</summary>
/// <returns>A JSON value-provider object for the specified controller context.</returns>
/// <param name="controllerContext">The controller context.</param>
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
if (controllerContext == null)
throw new ArgumentNullException("controllerContext");
object deserializedObject = CustomJsonValueProviderFactory.GetDeserializedObject(controllerContext);
if (deserializedObject == null)
return null;
Dictionary<string, object> strs = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
CustomJsonValueProviderFactory.AddToBackingStore(new CustomJsonValueProviderFactory.EntryLimitedDictionary(strs), string.Empty, deserializedObject);
return new DictionaryValueProvider<object>(strs, CultureInfo.CurrentCulture);
}
private static object GetDeserializedObject(ControllerContext controllerContext)
{
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
return null;
string fullStreamString = (new StreamReader(controllerContext.HttpContext.Request.InputStream)).ReadToEnd();
if (string.IsNullOrEmpty(fullStreamString))
return null;
var serializer = new JavaScriptSerializer()
{
MaxJsonLength = CustomJsonValueProviderFactory.GetMaxJsonLength()
};
return serializer.DeserializeObject(fullStreamString);
}
private static void AddToBackingStore(EntryLimitedDictionary backingStore, string prefix, object value)
{
IDictionary<string, object> strs = value as IDictionary<string, object>;
if (strs != null)
{
foreach (KeyValuePair<string, object> keyValuePair in strs)
CustomJsonValueProviderFactory.AddToBackingStore(backingStore, CustomJsonValueProviderFactory.MakePropertyKey(prefix, keyValuePair.Key), keyValuePair.Value);
return;
}
IList lists = value as IList;
if (lists == null)
{
backingStore.Add(prefix, value);
return;
}
for (int i = 0; i < lists.Count; i++)
{
CustomJsonValueProviderFactory.AddToBackingStore(backingStore, CustomJsonValueProviderFactory.MakeArrayKey(prefix, i), lists[i]);
}
}
private class EntryLimitedDictionary
{
private static int _maximumDepth;
private readonly IDictionary<string, object> _innerDictionary;
private int _itemCount;
static EntryLimitedDictionary()
{
_maximumDepth = CustomJsonValueProviderFactory.GetMaximumDepth();
}
public EntryLimitedDictionary(IDictionary<string, object> innerDictionary)
{
this._innerDictionary = innerDictionary;
}
public void Add(string key, object value)
{
int num = this._itemCount + 1;
this._itemCount = num;
if (num > _maximumDepth)
{
throw new InvalidOperationException("The length of the string exceeds the value set on the maxJsonLength property.");
}
this._innerDictionary.Add(key, value);
}
}
private static string MakeArrayKey(string prefix, int index)
{
return string.Concat(prefix, "[", index.ToString(CultureInfo.InvariantCulture), "]");
}
private static string MakePropertyKey(string prefix, string propertyName)
{
if (string.IsNullOrEmpty(prefix))
{
return propertyName;
}
return string.Concat(prefix, ".", propertyName);
}
private static int GetMaximumDepth()
{
int num;
NameValueCollection appSettings = ConfigurationManager.AppSettings;
if (appSettings != null)
{
string[] values = appSettings.GetValues("aspnet:MaxJsonDeserializerMembers");
if (values != null && values.Length != 0 && int.TryParse(values[0], out num))
{
return num;
}
}
return 1000;
}
private static int GetMaxJsonLength()
{
int num;
NameValueCollection appSettings = ConfigurationManager.AppSettings;
if (appSettings != null)
{
string[] values = appSettings.GetValues("aspnet:MaxJsonLength");
if (values != null && values.Length != 0 && int.TryParse(values[0], out num))
{
return num;
}
}
return 1000;
}
}
注:この回答はWebサービスにのみ適用されます。コントローラーメソッドからJSONを返す場合は、以下のSO答えも必ずお読みhttps://.com/a/7207539/1246870 : https://.com/a/7207539/1246870
MaxJsonLengthプロパティは無制限にすることはできません。デフォルトの102400(100k)の整数プロパティです。
web.configでMaxJsonLengthプロパティを設定できます:
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
</configuration>
このmaxJsonLengthの値がintの場合、そのint 32bit / 64bit / 16bitの大きさは....私はちょうど私のmaxJsonLengthとして設定できる最大値を確認したい
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483647">
</jsonSerialization>
</webServices>
</scripting>
この行をControllerに書くことができます
json.MaxJsonLength = 2147483644;
この行をweb.config
書き込むこともできます
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483647">
</jsonSerialization>
</webServices>
</scripting>
</system.web.extensions>
`
安全な側にいるためには、両方を使用してください。
ちょうどこれに遭遇した。 私は6,000以上のレコードを取得しています。 ちょうど私はちょうどいくつかのページングをすると決めました。 でのように、私はMVC JsonResultエンドポイントのページ番号を受け取ります。デフォルトでは0になっていますので、必要ありません。
public JsonResult MyObjects(int pageNumber = 0)
それでは、
return Json(_repository.MyObjects.ToList(), JsonRequestBehavior.AllowGet);
私は言う:
return Json(_repository.MyObjects.OrderBy(obj => obj.ID).Skip(1000 * pageNumber).Take(1000).ToList(), JsonRequestBehavior.AllowGet);
それはとても簡単です。 次に、JavaScriptでは、この代わりに:
function myAJAXCallback(items) {
// Do stuff here
}
私は代わりに言う:
var pageNumber = 0;
function myAJAXCallback(items) {
if(items.length == 1000)
// Call same endpoint but add this to the end: '?pageNumber=' + ++pageNumber
}
// Do stuff here
}
そして、あなたが最初にそれらと一緒にやっていたことにあなたの記録を追加してください。 または、すべての通話が終了して結果を一緒にまとめるまで待ってください。
モデルバインダー用に自動的に逆シリアル化されているJSON付きMVC3で問題が発生していて、サイズが大きすぎる場合は、ここでは解決策です。
- JsonValueProviderFactoryクラスのコードをMVC3ソースコードから新しいクラスにコピーします。
- オブジェクトを逆シリアル化する前に最大JSON長を変更する行を追加します。
- JsonValueProviderFactoryクラスを新しい変更クラスに置き換えます。
http://blog.naver.com/techshare/100145191355とhttps://gist.github.com/DalSoft/1588818おかげで、これを正しい方法で教えてくれてありがとう。 最初のサイトの最後のリンクには、ソリューションの完全なソースコードが含まれています。
単にMVJのActionメソッドでMaxJsonLengthをprprtyに設定する
JsonResult json= Json(classObject, JsonRequestBehavior.AllowGet);
json.MaxJsonLength = int.MaxValue;
return json;
属性マジックはどうですか?
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class MaxJsonSizeAttribute : ActionFilterAttribute
{
// Default: 10 MB worth of one byte chars
private int maxLength = 10 * 1024 * 1024;
public int MaxLength
{
set
{
if (value < 0) throw new ArgumentOutOfRangeException("value", "Value must be at least 0.");
maxLength = value;
}
get { return maxLength; }
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
JsonResult json = filterContext.Result as JsonResult;
if (json != null)
{
if (maxLength == 0)
{
json.MaxJsonLength = int.MaxValue;
}
else
{
json.MaxJsonLength = maxLength;
}
}
}
}
次に、グローバルフィルタ設定またはコントローラ/アクションワイズを使用して、グローバルに適用することができます。
次のようにweb.configを設定した後でもまだエラーが発生している場合:
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
</configuration>
私はそれを次のように解決しました:
public ActionResult/JsonResult getData()
{
var jsonResult = Json(superlargedata, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
これが助けてくれることを願っています
私はASP.NET Webフォームでこの問題を抱えていました。 これはweb.configファイルの設定を完全に無視していたので、私はこれを行いました:
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
return serializer.Serialize(response);
もちろん全体的にこれはひどい練習です。 Webサービスコールでこのように多くのデータを送信する場合は、別の方法を検討する必要があります。
私はvestigalの答えに続き、この解決策を得ました:
コントローラのアクションに大きなjsonをポストする必要があるとき、JSON JavaScriptSerializerを使用して非直列化中のエラーが発生します。文字列の長さはmaxJsonLengthプロパティで設定された値を超えます。パラメータ名:inputバリュープロバイダー "と呼ばれる。
私がしたことは、新しいValueProviderFactory、LargeJsonValueProviderFactoryを作成し、GetJeserializedObjectメソッドでMaxJsonLength = Int32.MaxValueを設定することです
public sealed class LargeJsonValueProviderFactory : ValueProviderFactory
{
private static void AddToBackingStore(LargeJsonValueProviderFactory.EntryLimitedDictionary backingStore, string prefix, object value)
{
IDictionary<string, object> dictionary = value as IDictionary<string, object>;
if (dictionary != null)
{
foreach (KeyValuePair<string, object> keyValuePair in (IEnumerable<KeyValuePair<string, object>>) dictionary)
LargeJsonValueProviderFactory.AddToBackingStore(backingStore, LargeJsonValueProviderFactory.MakePropertyKey(prefix, keyValuePair.Key), keyValuePair.Value);
}
else
{
IList list = value as IList;
if (list != null)
{
for (int index = 0; index < list.Count; ++index)
LargeJsonValueProviderFactory.AddToBackingStore(backingStore, LargeJsonValueProviderFactory.MakeArrayKey(prefix, index), list[index]);
}
else
backingStore.Add(prefix, value);
}
}
private static object GetDeserializedObject(ControllerContext controllerContext)
{
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
return (object) null;
string end = new StreamReader(controllerContext.HttpContext.Request.InputStream).ReadToEnd();
if (string.IsNullOrEmpty(end))
return (object) null;
var serializer = new JavaScriptSerializer {MaxJsonLength = Int32.MaxValue};
return serializer.DeserializeObject(end);
}
/// <summary>Returns a JSON value-provider object for the specified controller context.</summary>
/// <returns>A JSON value-provider object for the specified controller context.</returns>
/// <param name="controllerContext">The controller context.</param>
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
if (controllerContext == null)
throw new ArgumentNullException("controllerContext");
object deserializedObject = LargeJsonValueProviderFactory.GetDeserializedObject(controllerContext);
if (deserializedObject == null)
return (IValueProvider) null;
Dictionary<string, object> dictionary = new Dictionary<string, object>((IEqualityComparer<string>) StringComparer.OrdinalIgnoreCase);
LargeJsonValueProviderFactory.AddToBackingStore(new LargeJsonValueProviderFactory.EntryLimitedDictionary((IDictionary<string, object>) dictionary), string.Empty, deserializedObject);
return (IValueProvider) new DictionaryValueProvider<object>((IDictionary<string, object>) dictionary, CultureInfo.CurrentCulture);
}
private static string MakeArrayKey(string prefix, int index)
{
return prefix + "[" + index.ToString((IFormatProvider) CultureInfo.InvariantCulture) + "]";
}
private static string MakePropertyKey(string prefix, string propertyName)
{
if (!string.IsNullOrEmpty(prefix))
return prefix + "." + propertyName;
return propertyName;
}
private class EntryLimitedDictionary
{
private static int _maximumDepth = LargeJsonValueProviderFactory.EntryLimitedDictionary.GetMaximumDepth();
private readonly IDictionary<string, object> _innerDictionary;
private int _itemCount;
public EntryLimitedDictionary(IDictionary<string, object> innerDictionary)
{
this._innerDictionary = innerDictionary;
}
public void Add(string key, object value)
{
if (++this._itemCount > LargeJsonValueProviderFactory.EntryLimitedDictionary._maximumDepth)
throw new InvalidOperationException("JsonValueProviderFactory_RequestTooLarge");
this._innerDictionary.Add(key, value);
}
private static int GetMaximumDepth()
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
if (appSettings != null)
{
string[] values = appSettings.GetValues("aspnet:MaxJsonDeserializerMembers");
int result;
if (values != null && values.Length > 0 && int.TryParse(values[0], out result))
return result;
}
return 1000;
}
}
}
次に、Global.asax.csのApplication_Startメソッドで、ValueProviderFactoryを新しいものに置き換えます。
protected void Application_Start()
{
...
//Add LargeJsonValueProviderFactory
ValueProviderFactory jsonFactory = null;
foreach (var factory in ValueProviderFactories.Factories)
{
if (factory.GetType().FullName == "System.Web.Mvc.JsonValueProviderFactory")
{
jsonFactory = factory;
break;
}
}
if (jsonFactory != null)
{
ValueProviderFactories.Factories.Remove(jsonFactory);
}
var largeJsonValueProviderFactory = new LargeJsonValueProviderFactory();
ValueProviderFactories.Factories.Add(largeJsonValueProviderFactory);
}
私はこのコードを追加する問題を解決しました:
String confString = HttpContext.Current.Request.ApplicationPath.ToString();
Configuration conf = WebConfigurationManager.OpenWebConfiguration(confString);
ScriptingJsonSerializationSection section = (ScriptingJsonSerializationSection)conf.GetSection("system.web.extensions/scripting/webServices/jsonSerialization");
section.MaxJsonLength = 6553600;
conf.Save();