【问题标题】:Model binding to Dictionary<string,string> in Nancy模型绑定到 Nancy 中的 Dictionary<string,string>
【发布时间】:2015-05-28 16:23:10
【问题描述】:

我无法将 JSON 绑定到 Nancy 中的 Dictionary&lt;string,string&gt;

这条路线:

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&lt;string,string&gt;,如果可以,我在这里做错了什么?

【问题讨论】:

    标签: c# model-binding nancy


    【解决方案1】:

    Nancy 没有用于字典的built-in converter。因此,您需要像这样使用BindTo&lt;T&gt;()

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

    这将使用CollectionConverter。这样做的问题是它只会添加字符串值,所以如果你发送

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

    您的结果将仅包含密钥 hello

    如果您想将所有值捕获为字符串,即使它们没有按原样提供,那么您需要使用自定义 IModelBinder

    这会将所有值转换为字符串并返回Dictionary&lt;string, string&gt;

    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>());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-15
      • 2018-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多