Home > Blockchain >  How to configure json Name Case policy while using MinimalApi
How to configure json Name Case policy while using MinimalApi

Time:12-23

I'm trying to get result from my minimal API who configured in endpoints of my MVC web application my Get action configured like this :

            endpoints.MapGet(
                "HO-CFDZU4/api/Currency/Get", 
                [PermissionAuthorize(PermissionName.ReadCurrencyDictionary)] 
                async ([FromServicesAttribute] CurrencyService curency) =>
            {
                var result = await DataSourceLoader.LoadAsync(curency.Get(), new DataSourceLoadOptions());

                return Results.Ok(result);
            });

As result i get response with object where property names changed to lowercase, and its not suit for me. I want to get exactly same name in same case like i return form action.

To get similar effect in MVC i used this code :

            services
            .AddMvc()
            .AddFluentValidation(x => x.RegisterValidatorsFromAssembly(AppDomain.CurrentDomain.GetAssemblies().Where(x => x.FullName.Contains("ApplicationCore")).Single()))
            .AddMvcLocalization()
            .AddMvcOptions(options =>{})
            .AddRazorRuntimeCompilation()
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.PropertyNamingPolicy = null;
                options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
            });

Which setup property naming policy for Json while using action in controllers, and i dont know how to setup same policy for minimalApi.

What Ive tried is to set [JsonPropertyName(name)] And it working good but we have lot of classes and i looking for more global solution.

I also tried configure JsonOptions globally like this:

        services.Configure<JsonOptions>(options =>
        {
            options.JsonSerializerOptions.PropertyNamingPolicy = null;
            options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
        });

But it do nothing

CodePudding user response:

Use JsonOptions from Microsoft.AspNetCore.Http.Json namespace (docs):

services.Configure<JsonOptions>(options =>
{
    options.SerializerOptions.PropertyNamingPolicy = null;
    options.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});

UPD

If your application uses both Minimal APIs endpoints and MVC ones, then you try to configure options from both namespaces:

services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(options =>
{
    options.SerializerOptions.PropertyNamingPolicy = null;
    options.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});
services.Configure<Microsoft.AspNetCore.Mvc.JsonOptions>(options =>
{
    options.JsonSerializerOptions.PropertyNamingPolicy = null;
    options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});
  • Related