我无法将NSON绑定到Dictionary<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;
};
我得到例外:
值“[Hello,world]”不是“System.String”类型,不能 用于此通用集合。
是否可以使用Nancys默认模型绑定绑定到Dictionary<string,string>
,如果是这样,我在这里做错了什么?
答案 0 :(得分:5)
Nancy没有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;
}
}
Nancy会自动为您注册,您可以像往常一样绑定模型。
var data1 = this.Bind<Dictionary<string, string>>();
var data2 = this.BindTo(new Dictionary<string, string>());