c# - Nancy 模型绑定(bind)在 Chrome、IE 中不起作用

标签 c# javascript ajax nancy

我的一个应用程序中一直存在这个问题,我已将其剥离并设置了一个小型测试环境,但问题仍然存在。

我正在发布以下对象 (JSON)

{
    "eventName":"Testing from Services",
    "tickets":10,
    "_date":"10/10/2013",
    "_time":"8:00 PM",
    "ticketsLocation":"Testing from Services",
    "date":"2013-10-11T00:00:00.000Z"
}

使用下面的ajax调用

self.save = function (item, url, success) {
    $.ajax({
        type: "post",
        data: JSON.stringify(item),
        contentType: "application/json, charset=utf-8",
        traditional: true,
        datatype: "json",
        url: self.domain + url,
        success: success,
        error: self.error
    });
};

然后在服务端用下面的代码绑定(bind)数据

var Model = this.Bind<PropertyType>();

其中 PropertyType 是正确的类型(Event)。

这里是Event类供引用

public class Event
{
    public string EventName { get; set; }
    public int Tickets { get; set; }
    public Venue Venue { get; set; }
    public string TicketsLocation { get; set; }
    public DateTime Date { get; set; }
    public List<EventRequest> Requests { get; set; }
}

这在 Firefox 中工作得很好。在 Chrome 和 IE 中,Model 最终成为具有所有空值的 Event 对象。据我所知(通过使用 Fiddler),发布请求在所有浏览器之间完全相同。我还在其他机器上对此进行了测试,排除了我的机器和/或浏览器的问题。

有什么想法吗?我不明白浏览器如何影响 Nancy 模型绑定(bind)...

最佳答案

简单的回答是您的内容类型无效。没有诸如 application/json, charset=utf-8 内容类型之类的东西,尽管人们可能会告诉您。尽管 charset 是一个有效的、可选的、对内容类型的扩展,但它不适用于 application/json

您可以在这里阅读 http://www.ietf.org/rfc/rfc4627.txt?number=46276 IANA 考虑因素

部分下

The MIME media type for JSON text is application/json.

Type name: application

Subtype name: json

Required parameters: n/a

Optional parameters: n/a

关于编码的额外解释

Encoding considerations: 8bit if UTF-8; binary if UTF-16 or UTF-32

 JSON may be represented using UTF-8, UTF-16, or UTF-32.  When JSON
 is written in UTF-8, JSON is 8bit compatible.  When JSON is
 written in UTF-16 or UTF-32, the binary content-transfer-encoding
 must be used.

简而言之,JSON 已经是隐含的 utf-8。事实上,在 3 节下。编码它声明

JSON text SHALL be encoded in Unicode. The default encoding is UTF-8.

发送 application/json 就可以开始了

希望这有帮助:-)

关于c# - Nancy 模型绑定(bind)在 Chrome、IE 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17838109/

相关文章:

jquery - 使用 jquery ajax 下载 Excel 文件

c# - 在另一个数组中查找一个数组 (byte[])?

c# - 使用相同的证书进行 SSL 通信以及对 EXE 和 DLL 进行签名

c# - 正则表达式匹配所有字母数字和某些特殊字符?

javascript - 使用通过单击单独的 div 激活的灯箱集

javascript - 使用 AngularJs 在自定义 TinyMCE 编辑器中添加动态数据

ajax - 如何使用 Kaminari 为 Ajax 分页指定 Controller 和操作?

c# - 带有 VS 2010 的 Outlook 2013 加载项

javascript - React,将 onClick 事件直接添加到组件而不是在所述组件内渲染元素。

html - 获取动态加载的 HTML 内容的代码源(Chrome/Gmail)