模型绑定到 Nancy 中的 Dictionary<string,string>

Model binding to Dictionary<string,string> in Nancy

我无法在 Nancy 中将 JSON 绑定到 Dictionary<string,string>

这条路线:

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

    return Response.AsJson(dictionary);
};

returns 以下 JSON,符合预期:

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

当我尝试 post 这条确切的 JSON 回到这条路线时:

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

我得到异常:

The value "[Hello, world]" is not of type "System.String" and cannot be used in this generic collection.

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

南希没有 built-in converter 字典。因此,您需要像这样使用 BindTo<T>()

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

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

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

您的结果将只包含键 hello

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

这会将所有值转换为字符串和 return 一个 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)
    {
        // 
        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>());