Skip to content

Instantly share code, notes, and snippets.

@emadb
Forked from thecodejunkie/DynamicModelBinder.cs
Last active August 16, 2018 11:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emadb/6087812 to your computer and use it in GitHub Desktop.
Save emadb/6087812 to your computer and use it in GitHub Desktop.
A DynamicModelBinder for NancyFx (http://nancyfx.org/). It convert your request data (form, body, querystring) into a dynamic model. This means that you don't have to create all your useless DTO. NOTE. The original version is here https://gist.github.com/thecodejunkie/5521941 (thecodejunkie). I simply add the support for deserialize the request …
public static class DynamicBinderExtensions
{
public static dynamic DynaBind(this INancyModule module)
{
return module.Bind<DynamicDictionary>();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using Nancy.ModelBinding;
using Newtonsoft.Json;
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)
{
IDictionary<string, string> body = GetBody(context);
return Merge(new IDictionary<string, string>[]
{
ConvertDynamicDictionary(context.Request.Form),
ConvertDynamicDictionary(context.Request.Query),
body,
ConvertDynamicDictionary(context.Parameters)
});
}
private static IDictionary<string, string> GetBody(NancyContext context)
{
IDictionary<string, string> body = null;
if (context.Request.Body != null)
{
TextReader te = new StreamReader(context.Request.Body);
body = JsonConvert.DeserializeObject<Dictionary<string, string>>(te.ReadToEnd());
}
return body;
}
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);
}
}
Get["/dynamic/{name}"] = parameters => {
dynamic model = this.DynaBind();
return Response.AsJson(model);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment