Skip to content

Instantly share code, notes, and snippets.

@thecodejunkie
Created May 5, 2013 19:41
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save thecodejunkie/5521941 to your computer and use it in GitHub Desktop.
Save thecodejunkie/5521941 to your computer and use it in GitHub Desktop.
Binding to a DynamicDictionary
using System;
using System.Collections.Generic;
using System.Linq;
using Nancy.ModelBinding;
public class DynamicModelBinder : IModelBinder
{
public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList)
{
var data =
GetDataFields(context);
var model =
DynamicDictionary.Create(data);
return model;
}
private static IDictionary<string, object> GetDataFields(NancyContext context)
{
return Merge(new IDictionary<string, string>[]
{
ConvertDynamicDictionary(context.Request.Form),
ConvertDynamicDictionary(context.Request.Query),
ConvertDynamicDictionary(context.Parameters)
});
}
private static IDictionary<string, object> Merge(IEnumerable<IDictionary<string, string>> dictionaries)
{
var output =
new Dictionary<string, object>(StringComparer.InvariantCultureIgnoreCase);
foreach (var dictionary in dictionaries.Where(d => d != null))
{
foreach (var kvp in dictionary)
{
if (!output.ContainsKey(kvp.Key))
{
output.Add(kvp.Key, kvp.Value);
}
}
}
return output;
}
private static IDictionary<string, string> ConvertDynamicDictionary(DynamicDictionary dictionary)
{
return dictionary.GetDynamicMemberNames().ToDictionary(
memberName => memberName,
memberName => (string)dictionary[memberName]);
}
public bool CanBind(Type modelType)
{
return modelType == typeof (DynamicDictionary);
}
}
Can be invoked using
http://localhost:40965/dynamic/nancy?age=10&value=test
Which would give you the following output
{
"age": "10",
"value": "test",
"name": "nancy"
}
Get["/dynamic/{name}"] = parameters => {
var model =
this.Bind<DynamicDictionary>();
return Response.AsJson(model);
};
@maeishoj
Copy link

maeishoj commented Oct 2, 2014

How can you make this work with post requests instead? Meaning, how can I just send a POST request with json to http://localhost:40965/addUser and bind that dynamically to a variable?

@GusBeare
Copy link

GusBeare commented May 4, 2017

I couldn't get this to work with a POST and Json in the Body. I finally found this: http://stackoverflow.com/questions/16722311/nancyfx-binding-a-model-to-a-dynamic-type
Check out the answer by @maki using Json.Net. It worked for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment