c# - Nancy FX 在模型绑定(bind)上将字典中的键大写

标签 c# json model-binding nancy

我正在尝试将 JSON 发布到 NancyFx。 JSON 如下:

{  
   "prop1": 1,
   "entries":{  
      "Entry1": 1,
      "entry2": 2
   }
}

在服务器端我创建了一个相应的模型:

public class Model
{
    public int Prop1 { get; set; }
    public IDictionary<string, object> Entries { get; set; }
}

entries JSON 中的字段具有动态结构,因此 IDictionary<string, object>在模型中使用。

然后我绑定(bind)模型:

this.Bind<Model>();

模型已成功创建,但问题在于 Entries字典的两个键都是大写的。对我来说,大小写非常重要,我希望第二个 key 是 entry2,而不是 E/strong>ntry2.

我也尝试使用 JavaScriptConverterJavaScriptPrimitiveConverter但在 Deserialize方法我得到已经大写的数据。

有什么解决办法吗?

最佳答案

对我来说,这是通过配置 JavascriptSerializer 来保留大小写来解决的。

不幸的是,我想不出一个干净的方法来做到这一点,但这是我现在使用的 hack。

    public class Model
    {
        public IDictionary<string, object> Entries { get; set; }
    }

    public class CustomModelBinder : IModelBinder
    {

        public bool CanBind(Type modelType)
        {
            return modelType == typeof(Model);
        }

        public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList)
        {
            using (var sr = new StreamReader(context.Request.Body))
            {
                return (new JavaScriptSerializer() { RetainCasing = true }).Deserialize<Model>(sr.ReadToEnd());
            }
        }
    }

Nancy 将在运行时获取此 Binder ,无需显式注册任何内容。

这个解决方案并不理想,因为它忽略了一些 Nancy 功能,例如黑名单和其他可能的绑定(bind)配置设置。

关于c# - Nancy FX 在模型绑定(bind)上将字典中的键大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31817172/

相关文章:

c# - .NET 安全机制限制同一项目中两种类型之间的访问?

javascript - Ajax在php中提交表单序列化数据为空

html - ASP.NET MVC 模型列表绑定(bind)

asp.net-mvc-4 - 如何防止复杂类型的默认绑定(bind)器?

C# 使用反射设置 Dictionary<String, Object> 值

c# - 单例线程安全

c# - C# 中类库的全局错误处理程序

json - 如何使用 SSIS 将 json 从 Azure Blob 加载到 SQL Server?

python - 无法从延迟加载网站获取某些标签

asp.net-core - 如何在 MVC Core 中绑定(bind)数组