4

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

我发布以下对象(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),所有浏览器之间的发布请求完全相同。我还在其他机器上对此进行了测试,排除了我的机器和/或浏览器的问题。

有任何想法吗?我不明白浏览器如何影响 Nancy 模型绑定......

4

1 回答 1

9

简单的答案是您的内容类型无效。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

必需参数:不适用

可选参数:不适用

附带关于编码的附加说明

编码注意事项:如果是 UTF-8,则为 8bit;如果是 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,你应该准备去

希望这可以帮助 :-)

于 2013-07-24T22:49:19.233 回答