Loading ...

Manage Serialization In Net Core 2 0

Hello everybody,

today I want to write a short notice on how to manage uppercase/lowercase options for serialization in .Net Core.

In mine practice I often had situation, when javascript or typescript code sends me some staff in lowercase class names, but in C# I'm used to Upper case class names. 

Another option that you sometime can need is switching between xml and json serialization. How those options can be managed in .Net Core 2.0 ?

For both of those options ( and even more ) you can use pipeline management of Startup class of ConfigureServices method.

For example if you need to have xml serialization output you can use following code:

public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc()
                .AddMvcOptions(o => o.OutputFormatters.Add(
                    new XmlDataContractSerializerOutputFormatter()));

 

And if you want to switch default naming from camel case to Upper case, then following code in Startup class can be added:

public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc()
                .AddJsonOptions(o =>
                {
                    if (o.SerializerSettings.ContractResolver != null)
                    {
                        var castedResolver = o.SerializerSettings.ContractResolver
                            as DefaultContractResolver;
                        castedResolver.NamingStrategy = null;
                    }
                });
        }

 

with such changes you can easier or harder to manipulate your input/output from .Net MVC controllers