Nancy模型绑定在Chrome、IE中不起作用

本文关键字:IE 不起作用 Chrome 模型 绑定 Nancy | 更新日期: 2023-09-27 18:24:39

我的一个应用程序中遇到了这个问题,我已经将其剥离,并设置了一个小的测试环境,在这个环境中仍然会出现这个问题。

我正在发布以下对象(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
    });
};

然后在服务器上用以下代码绑定数据

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),所有浏览器之间的post请求完全相同。我也在其他机器上测试过这一点,排除了我的机器和/或浏览器的问题。

有什么想法吗?我不明白浏览器是如何影响Nancy模型绑定的。。。

Nancy模型绑定在Chrome、IE中不起作用

简单的答案是您的内容类型无效。不存在application/json, charset=utf-8内容类型这样的东西,尽管人们可能会告诉你。尽管charset是内容类型的有效、可选扩展,但它不适用于application/json

你可以在这里阅读http://www.ietf.org/rfc/rfc4627.txt?number=4627根据6 IANA considerations

JSON文本的MIME媒体类型为application/JSON。

类型名称:应用

子类型名称:json

所需参数:无

可选参数:n/a

关于编码的附加说明

编码注意事项:如果是UTF-8,则为8位;二进制,如果是UTF-16或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. Encoding节中,它说明了

JSON文本应采用Unicode编码。默认编码为UTF-8。

发送application/json,您应该设置为进入

希望这有帮助:-)