Before .net core technology we can add maxjson size in web.config .but in .net core how to set max json size? and where?
-
It says here that it cannot be done, although this was a year ago so not sure if it has changed: https://forums.asp.net/post/6194371.aspx – andyb952 Aug 28 '19 at 11:23
-
This may also be useful https://github.com/JamesNK/Newtonsoft.Json/issues/1694 – andyb952 Aug 28 '19 at 11:23
2 Answers
You would need to manage this at the serialization level. Not sure if you are using the new Microsoft Json serialization or NetwtonSoft.
When Microsoft you need to use the DataContractJsonSerializer, when NetwontSoft have a look at mel-green's solution, you can substitute the progress with bytes size and throw an error if to big. another option is to use options and set your own ITraceWriter that doesn't trade but throw an error when to big.
A tip, when using Json you can decorate properties as to you can shorten the property names. like so:
[JsonProperty("A1")]
private int SomeReallyLongPropertyName;
Make sure though not to make duplicate names, json will then map via the alias.
another way to make the json shorter is by converting it into something smaller.
[JsonConverter(typeof(UTCDateTimeConverter))]
[JsonProperty("DT")]
public DateTime Date { get; set; }
the converter:
public sealed class UTCDateTimeConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTime?);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value is null) return null;
try
{
return new DateTime((long)reader.Value);
}
catch
{
if (DateTime.TryParse(reader.Value.ToString(), out DateTime d))
return d;
else
return null;
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var val = ((DateTime)value).Ticks;
writer.WriteValue(val);
}
}
You can also decorate the class you like to convert to warn if the size is to large by implementing the above and change the implementation of WriteJson to monitor your size however that not what you asked as it it doesn't address the whole stream.

- 9,150
- 8
- 69
- 117

- 3,867
- 27
- 36
You can handle this at serialization level. Have you tried doing something like below?
// Creates an instance of your JavaScriptSerializer
// and Setting the MaxJsonLength
var serializer = new JavaScriptSerializer() { MaxJsonLength = 86753090 };
// Perform your serialization
serializer.Serialize("Your JSON Contents");

- 27
- 6
-
[`JavaScriptSerializer`](https://learn.microsoft.com/en-us/dotnet/api/system.web.script.serialization.javascriptserializer?view=netcore-3.1) has not been ported to .NET Core, so this answer will not work there. It is unlikely that it will be ported given that MSFT is developing the new serializer [tag:system.text.json]. – dbc Apr 02 '21 at 20:18