Set Asp.Net Core MVC Json Options

One of the classes that I have in my project called AChas a property of Addresstype IPEndPoint. This type, as well as IPAddress, appears to be incompatible with default JSON serialization. Since I needed to serialize my class, I implemented two custom converters: IPAddressConverterand IPEndPointConverter. To get Newtonsoft to use these two converters, I made this class:

public sealed class CustomSettings : JsonSerializerSettings
{
    public CustomSettings() : base()
    {
        this.Converters.Add(new IPAddressConverter());
        this.Converters.Add(new IPEndPointConverter());
        this.TypeNameHandling = TypeNameHandling.Auto;
    }
} 

.. which I use in mine Mainlike this:

Newtonsoft.Json.JsonConvert.DefaultSettings = () => new CustomSettings();

Now I am trying to add an API to my program. I created a .Net Core Web API project and successfully integrated it into my program. However, problems arose when I tried to write a POST method that required ACa JSON instance from the request body. The serializer could not convert IPEndPoint, and therefore ACthere has always been a value null.

API configuration information. Core Core is pretty rare. Can someone tell me how can I pass the same settings to the MVC serializer?

EDIT

I found a way (sort of). Turns out you can set the JSON parameters in the method ConfigureServices.

I tried to change the settings of the MVC serializer in the same way as for the rest of my program by doing the following:

services.AddMvc().AddJsonOptions(options => options.SerializerSettings = new CustomSettings());

However, this does not work as it options.SerializerSettingsis read only.

, , ( CustomSettings). ?

+12
1

, ,

public static void AddCustomSettings(this Newtonsoft.Json.JsonSerializerSettings settings) {
    settings.Converters.Add(new IPAddressConverter());
    settings.Converters.Add(new IPEndPointConverter());
    settings.TypeNameHandling = TypeNameHandling.Auto;
}

ConfigureServices

services.AddJsonOptions(options => options.SerializerSettings.AddCustomSettings());
+10

Source: https://habr.com/ru/post/1677379/


All Articles