Dav*_*e S 6 c# model-binding nancy
我无法Dictionary<string,string>在Nancy中绑定JSON .
这条路线:
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"类型,不能在此通用集合中使用.
是否可以绑定到Dictionary<string,string>使用Nancys默认模型绑定,如果是这样,我在这里做错了什么?
Nancy没有用于词典的内置转换器.因此,您需要BindTo<T>()像这样使用
var data = this.BindTo(new Dictionary<string, string>());
哪个会使用CollectionConverter.像这样做的问题是它只会添加字符串值,所以如果你发送
{
    "hello": "world",
    "foo": 123
}
您的结果只包含密钥hello.
如果要将所有值捕获为字符串,即使它们不是这样提供的,那么您还需要使用自定义IModelBinder.
这会将所有值转换为字符串并返回a 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>());
| 归档时间: | 
 | 
| 查看次数: | 2452 次 | 
| 最近记录: |