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