Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I increase the JSON deserialization MaxDepth limit in my ASP.NET Core webapp

We're using ASP.NET Core 2.1 with .NET Framework 4.6.2.

We have a customer who needs to send up a rather largely nested json structure to our webapp.

When they make this call, we're outputting the following log and returning an error:

The reader's MaxDepth of 32 has been exceeded. Path 'super.long.path.to property', line 1, position 42111."

I've looked through the ASP.NET Core codebase, and have observed a couple of references to MaxDepth = 32 in the deserializer provided with the framework.

Is it possible to configure this to a different depth?

like image 296
ElFik Avatar asked Sep 27 '19 16:09

ElFik


People also ask

What is Maxdepth in JSON?

Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a JsonReaderException. A null value means there is no maximum. The default value is null.

Is Newtonsoft JSON compatible with .NET core?

See the version list below for details. ASP.NET Core MVC features that use Newtonsoft. Json. Includes input and output formatters for JSON and JSON PATCH.

Should I use Newtonsoft or System text JSON?

By default, Newtonsoft. Json does case insensitive property name matching during deserialization whereas System. Text. Json does case sensitive matching (with exception in ASP.Net core where you don't need to do anything to achieve behavior like Newtonsoft.

Is Newtonsoft JSON obsolete?

Obsolete. The value types allowed by the JsonSchema. JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.


3 Answers

I have not tested this, but in Startup.cs you should be able to do something like this:

services.AddMvc().AddJsonOptions(options => {
    options.SerializerSettings.MaxDepth = 64;  // or however deep you need
});
like image 136
Brian Rogers Avatar answered Nov 14 '22 22:11

Brian Rogers


You could also set depth you need directly in deserialization as shown in the following example:

JsonConvert.DeserializeObject< T >(json, new JsonSerializerSettings
{
    MaxDepth = //the value you need
});
like image 32
Xueli Chen Avatar answered Nov 14 '22 23:11

Xueli Chen


If you are using .NET Core 3.1, try this in your startup.cs file. Make sure to install the Newtonsoft.Json package.

services.AddMvc().AddNewtonsoftJson(options =>
{
    options.SerializerSettings.MaxDepth = 64;
});
like image 38
Mukesh Salaria Avatar answered Nov 14 '22 22:11

Mukesh Salaria