【问题标题】:Nancy model binding not working in Chrome, IENancy 模型绑定在 Chrome、IE 中不起作用
【发布时间】:2013-07-24 04:06:04
【问题描述】:

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

我正在发布以下对象 (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 模型绑定...

【问题讨论】:

    标签: c# javascript ajax nancy


    【解决方案1】:

    简单的答案是您的内容类型无效。没有 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,您应该可以出发了

    希望这会有所帮助:-)

    【讨论】:

    • 哇,我不敢相信是这样。感谢您的帮助。
    猜你喜欢
    • 2017-07-26
    • 1970-01-01
    • 2012-07-23
    • 2012-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多