Home > Enterprise >  How can i add net5.0 Worker Application AddJsonOptions
How can i add net5.0 Worker Application AddJsonOptions

Time:01-19

There are API project and Worker project in the solution. The API project is written in net5.0 Microsoft.NET.Sdk.Web. In Startup.cs

services.AddControllers().AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.IgnoreNullValues = true;
                options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); // for enum as strings
            });

This code block is available in Startup.cs.

I also want to add these JsonOptions to net5.0 Worker project but Controller and Startup.cs are not available in worker project. How can i add?

I tried this

services.AddControllers()
    .AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.ContractResolver = new DefaultContractResolver();
    });

and this

services.AddMvc().AddJsonOptions(o =>
{
    o.JsonSerializerOptions.PropertyNamingPolicy = null;
    o.JsonSerializerOptions.DictionaryKeyPolicy = null;
});

but not works for me

CodePudding user response:

AddJsonOptions are only used to bind/send json via endpoints, worker project does not expose any endpoints (at least by default), so there is no point adding them unless you resolve IOptions<JsonOptions> somewhere in the code directly. In this case you can always call Configure:

services.Configure<JsonOptions>(options =>
{
    options.JsonSerializerOptions.IgnoreNullValues = true;
    options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); // for enum as strings
});
  • Related