Nancy FX capitalizes dictionaries keys in model binding

I am trying to send JSON to NancyFx. JSON:

{ "prop1": 1, "entries":{ "Entry1": 1, "entry2": 2 } } 

On the server side, I created an appropriate model:

 public class Model { public int Prop1 { get; set; } public IDictionary<string, object> Entries { get; set; } } 
Field

entries in JSON has a dynamic structure, and because of this, the model uses IDictionary<string, object> .

And then I bind the model:

 this.Bind<Model>(); 

The model was created successfully, but the problem is that in the entries dictionary both keys are in the capital case. For me, the matter is very important, and I expect that the second key will be e ntry2, not E ntry2.

I also tried using JavaScriptConverter and JavaScriptPrimitiveConverter , but in the Deserialize method I got the header data already.

Any ideas on how to fix this?

+4
source share
2 answers

For me, this was solved by configuring the JavascriptSerializer to save the shell.

Unfortunately, I could not figure out how to do this, but here is the hack I am using now.

  public class Model { public IDictionary<string, object> Entries { get; set; } } public class CustomModelBinder : IModelBinder { public bool CanBind(Type modelType) { return modelType == typeof(Model); } public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList) { using (var sr = new StreamReader(context.Request.Body)) { return (new JavaScriptSerializer() { RetainCasing = true }).Deserialize<Model>(sr.ReadToEnd()); } } } 

Nancy will take this binder at runtime; there is no need to explicitly register anything.

This solution is not ideal because it ignores some of Nancy's features, such as blacklists and possibly other binding configuration settings.

+1
source

The best option is to install JsonSettings from Bootstrapper.

 public class MyBootstrapper : DefaultNancyBootstrapper { public MyBootstrapper () : base() { JsonSettings.RetainCasing = true; } } 

The IModelBinder implementation works, but it spoils the other default binding settings.

0
source

All Articles