Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nancy model binding not working in Chrome, IE

I have been having this issue in one of my applications and have stripped it down and set up a small test environment in which the problem still occurs.

I am posting the following object (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"
}

using the following ajax call

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
    });
};

and then binding the data with the following code on the server

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

where PropertyType is the correct type (Event).

Here is the Event class for reference

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; }
}

This works perfectly fine in Firefox. In Chrome and IE, Model ends up being an Event object with all null values. As far as I can tell (by using Fiddler), the post request is exactly the same between all browsers. I have also tested this on other machines, ruling out my machine and/or browsers as the issue.

Any ideas? I don't understand how the browser affects Nancy model binding...

like image 799
acurcie Avatar asked Jan 13 '23 20:01

acurcie


1 Answers

The simple answer is that your content-type is invalid. There is no such thing as an application/json, charset=utf-8 content type, despite what people might tell you. Even though charset is a valid, optional, extension to content-type it does not apply to application/json

You can read about this here http://www.ietf.org/rfc/rfc4627.txt?number=4627 under section 6 IANA considerations

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

Type name: application

Subtype name: json

Required parameters: n/a

Optional parameters: n/a

With the additional explanation about encoding

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.

In short, JSON is already, implicitly, utf-8. In fact, under section 3. Encoding it states

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

Send in application/json and you should be set to go

Hope this helps :-)

like image 107
TheCodeJunkie Avatar answered Jan 21 '23 17:01

TheCodeJunkie