Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add NewtonSoft SerializerSettings globally in startup when PiranhaManager is present #1354

Closed
aaguilera88 opened this issue Sep 30, 2020 · 8 comments
Assignees
Milestone

Comments

@aaguilera88
Copy link

Hello everyone.
I have an existing .NET Core 3.1 project which needs to set the NewtonSoft SerializerSettings contract resolver to be the ContractResolver. The problem is, when i setup this and include the services and middleware relative to PiranhaManager, the serializer settigns are ignored. This is my actual startup (with the piranhamanager commented to made the application works).

Can some one help me with this issue?

 public void ConfigureServices(IServiceCollection services)
        {
            //Culture
            services.Configure<RequestLocalizationOptions>(options =>
            {
                options.DefaultRequestCulture = new RequestCulture("es-MX");
                options.SupportedCultures = new List<CultureInfo> { new CultureInfo("es-MX") };

            });
            //Syncfusion
            Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("");

            //DB Context
            services.AddDbContext<HammurabiSistemaContext>(options => options.UseSqlServer(_config.GetConnectionString("Ham"), b => b.MigrationsAssembly("HammurabiWeb")));
            //Repositorios
            services.AddScoped<IRepository, Repository<HammurabiSistemaContext>>();
            //Identity
            services.AddIdentity<IdentityUser, IdentityRole>(opt =>
            {
                opt.Password.RequiredLength = 7;
                opt.Password.RequireDigit = false;
                opt.Password.RequireUppercase = false;
                opt.Password.RequireNonAlphanumeric = false;
            })
           .AddEntityFrameworkStores<HammurabiSistemaContext>()
           .AddDefaultTokenProviders();
            //Custom claims
            services.AddScoped<IUserClaimsPrincipalFactory<IdentityUser>, CustomClaimsFactory>();
            //App Cookie
            services.ConfigureApplicationCookie(options =>
            {
                options.AccessDeniedPath = new PathString("/Sistema/Home/AccessDenied");
                options.LoginPath = new PathString("/Sistema/Home/Login");
                options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
                options.SlidingExpiration = true;
            });
            //Autorizacion
            services.AddAuthorization(options =>
            {
                options.AddPolicy("ResourceAccessSistema", policy => policy.Requirements.Add(new ResourceAccessRequirementSistema()));
            });
            services.AddScoped<IAuthorizationHandler, ResourceAccessHandlerSistema>();

            // Configure controllers with Localization
            services.AddControllersWithViews()
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                options.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
                options.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
            });
            // Configure Razor Pages with json serializer
            services.AddRazorPages()
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                options.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
                options.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
            })
            .AddRazorRuntimeCompilation();
            //.AddPiranhaManagerOptions();

            // Add PiranhaCMS
            services.AddPiranha();
            services.AddPiranhaApplication();
            services.AddPiranhaBlobStorage(_config.GetConnectionString("blobstorage"));
            services.AddPiranhaImageSharp();
            //services.AddPiranhaManager();
            services.AddPiranhaTinyMCE();
            services.AddPiranhaMemoryCache();
            services.AddPiranhaEF<SQLServerDb>(db => db.UseSqlServer(_config.GetConnectionString("Ham")));

            // http context
            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            // Implementación de ISecurity para Manager de Piranha
            services.AddTransient<Piranha.ISecurity, CustomPiranhaSecurity>();
            //Twilio
            services.AddScoped<IMessage, SmsMessage>();
        }


        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IApi api)        
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // Initialize Piranha
            App.Init(api);

            // Build content types
            new ContentTypeBuilder(api)
                .AddAssembly(typeof(Startup).Assembly)
                .Build()
                .DeleteOrphans();

            // Configure Tiny MCE
            EditorConfig.FromFile("editorconfig.json");

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            // Add call to use Piranha
            app.UsePiranha();

            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();

            // Configure Piranha            
            //app.UsePiranhaManager();
            app.UsePiranhaTinyMCE();

            //culture
            var cultureInfo = new CultureInfo("es-MX");
            CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
            CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

                endpoints.MapControllerRoute(
                name: "areas",
                pattern: "{area}/{controller=Home}/{did?}/{action=Index}/{id?}");

                endpoints.MapRazorPages();

               // endpoints.MapPiranhaManager();

            });

           
        }
@tidyui
Copy link
Member

tidyui commented Sep 30, 2020

Good point, we’ll take a look at how we can achieve this. The reason Piranha sets this up internally is that it also needs to configure the JsonOptions in order to work.

https://github.com/PiranhaCMS/piranha.core/blob/master/core/Piranha.Manager/ManagerExtensions.cs#L267

@tidyui tidyui added this to the Version 9.0 milestone Sep 30, 2020
@aaguilera88
Copy link
Author

Great. Hope you can find a way. THX

@zoinkydoink
Copy link

FYI, given that .NET 5 has better support built in for Json (System.Text.Json), might look into implementing that where possible instead of Newtonsoft

@tidyui
Copy link
Member

tidyui commented Oct 12, 2020

Hi there @zoinkydoink. We will look into System.Text.Json when we start the migration process to .NET 5. The reason for not using it in .NET Core 3 is that it doesn't support serialization of properties which are declared as interfaces or base classes, it only serializes finite types.

@zoinkydoink
Copy link

zoinkydoink commented Oct 12, 2020

Yes the support of System.Json.Text in 3.1 is purely garbage, I thought I would throw that comment in there about .NET 5 because it is suppose to have a lot of newtonsoft functionality.

@tidyui
Copy link
Member

tidyui commented Oct 12, 2020

We will most likely not be able to use System.Text.Json until Microsoft releases a LTS release, because up to that point we most likely need to compile for multiple targets supporting both 3.1 (since it's LTS) and 5.

@tidyui
Copy link
Member

tidyui commented Oct 12, 2020

Which according to their release plan seems to be 6.0 scheduled for November 2021.

@tidyui tidyui closed this as completed in f75594f Dec 15, 2020
@tidyui
Copy link
Member

tidyui commented Dec 15, 2020

This will be available in ConfigureService when calling UseManager()

services.AddPiranha(options =>
{
    ...

    options.UseManager(jsonOptions =>
    {
        ...
    });

    ...
});

@tidyui tidyui self-assigned this Jan 19, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants