Skip to content

Instantly share code, notes, and snippets.

Revisions

  1. @thecodejunkie thecodejunkie created this gist May 5, 2013.
    59 changes: 59 additions & 0 deletions DynamicModelBinder.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    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);
    }
    }
    6 changes: 6 additions & 0 deletions Module.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,6 @@
    Get["/dynamic/{name}"] = parameters => {
    var model =
    this.Bind<DynamicDictionary>();

    return Response.AsJson(model);
    };
    12 changes: 12 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    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"
    }