2015-05-28 23 views
5

我无法将JSON绑定到南希的Dictionary<string,string>模型绑定到南希的词典<string,string>

这条路线:

Get["testGet"] = _ => 
{ 
    var dictionary = new Dictionary<string, string> 
    { 
     {"hello", "world"}, 
     {"foo", "bar"} 
    }; 

    return Response.AsJson(dictionary); 
}; 

返回以下JSON,符合市场预期:

{ 
    "hello": "world", 
    "foo": "bar" 
} 

当我尝试发布这一确切JSON回这条路线:

Post["testPost"] = _ => 
{ 
    var data = this.Bind<Dictionary<string, string>>(); 
    return null; 
}; 

我获得例外:

值“[你好,世界]”不是“System.String”类型,不能在此泛型集合中使用 。

是否可以使用Nancys的默认模型绑定绑定到Dictionary<string,string>,如果是这样,我在这里做错了什么?

回答

5

南希没有用于词典的built-in converter。正因为如此,你就需要使用BindTo<T>()像这样

var data = this.BindTo(new Dictionary<string, string>()); 

其中会使用到CollectionConverter。与做这样的问题是它只会增加字符串值,因此,如果您发送

{ 
    "hello": "world", 
    "foo": 123 
} 

你的结果将只包含关键hello

如果你想捕获所有的值作为字符串,即使它们不是这样提供的,那么你需要使用自定义的IModelBinder

这会将所有值转换为字符串并返回Dictionary<string, string>

public class StringDictionaryBinder : IModelBinder 
{ 
    public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList) 
    { 
     var result = (instance as Dictionary<string, string>) ?? new Dictionary<string, string>(); 

     IDictionary<string, object> formData = (DynamicDictionary) context.Request.Form; 

     foreach (var item in formData) 
     { 
      var itemValue = Convert.ChangeType(item.Value, typeof (string)) as string; 

      result.Add(item.Key, itemValue); 
     } 

     return result; 
    } 

    public bool CanBind(Type modelType) 
    { 
     // http://stackoverflow.com/a/16956978/39605 
     if (modelType.IsGenericType && modelType.GetGenericTypeDefinition() == typeof (Dictionary<,>)) 
     { 
      if (modelType.GetGenericArguments()[0] == typeof (string) && 
       modelType.GetGenericArguments()[1] == typeof (string)) 
      { 
       return true; 
      } 
     } 

     return false; 
    } 
} 

南希会自动为您注册,您可以像平常一样绑定您的模型。

var data1 = this.Bind<Dictionary<string, string>>(); 
var data2 = this.BindTo(new Dictionary<string, string>()); 
相关问题