NancyFx / Nancy

Lightweight, low-ceremony, framework for building HTTP based services on .Net and Mono
http://nancyfx.org
MIT License
7.15k stars 1.47k forks source link

Json response contains lowercase letters, when dictionary keys contain capital letters #2945

Closed michaelkruglos closed 5 years ago

michaelkruglos commented 5 years ago

Prerequisites

Description

Json response contains lowercase letters, when dictionary keys contain capital letters. Expected response: { "Key": "value" } Actual: { "key": "value" }

Steps to Reproduce

var dictionary = new Dictionary<string,string>(); dictionary["Key"] = "value"; return Response.AsJson(dictionary);

System Configuration

.NET Core 2.1

cloudhunter89 commented 5 years ago

This is the default behavior of the default serialization. It converts to camelCase. There is an option to retain casing. #1484 provides some discussion on the topic. In 1.4, there is Nancy.Json.JsonSettings.RetainCasing that can be set to true to prevent the default de/serializer from changing case. I've never used 2.0.0, but a similar member exists on Nancy.Json.JsonConfiguration -- though I haven't figured out where to create and pass that in yet...

michaelkruglos commented 5 years ago

After hours of reading code and experimentation, I figured out you need to supply your own bootstrapper to Nancy, where you override Configure method and register your own JSON configuration. Example:

    internal class MyBootstrapper : DefaultNancyBootstrapper
    {
        public override void Configure(INancyEnvironment environment)
        {
            base.Configure(environment);
            var defaultJsonConfig = JsonConfiguration.Default;
            environment.Json(null, defaultJsonConfig.DefaultEncoding, defaultJsonConfig.Converters, defaultJsonConfig.PrimitiveConverters, true, true);
        }
    }

Read the code of Json extension method to understand how to use it. I think V2 needs a serious documentation effort. I know it's in pre-release, but it's the only Nancy that runs on .NET Core.