Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Asp.Net Core MVC Json options

One of the classes that I have in my project called, say, AC, has a property Address that is of type IPEndPoint. This type, as well as IPAddress, are notorious for not being serializable to JSON by default. Since I needed to serialize my class, I implemented two custom converters: IPAddressConverter and IPEndPointConverter. To make Newtonsoft 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 my Main like so:

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

Now I am trying to add an API to my program. I have created a .Net Core Web API project and have integrated it into my program successfully. However, problems arose when I attempted to write a POST method that required an instance of AC in JSON form from the request body. The serializer couldn't convert the IPEndPoint, and thus the value of AC was always null.

Information regarding configuration of .Net Core APIs is pretty sparse. Can anyone tell me how I can pass those same settings to the MVC's serializer?

EDIT

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

I attempted to modify the MVC's serializer's settings the same way I did for the rest of my program by doing this:

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

However, this doesn't work as options.SerializerSettings is read only.

I could pass the converters one by one, but I'd prefer if they were all managed from one place (the CustomSettings class). Is this possible?

like image 298
stelioslogothetis Avatar asked May 17 '17 18:05

stelioslogothetis


1 Answers

Create an extension method that encapsulates what it is you want configured

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

And configure it in ConfigureServices

services.AddJsonOptions(options => options.SerializerSettings.AddCustomSettings());
like image 121
Nkosi Avatar answered Oct 18 '22 01:10

Nkosi