How to solve Invalid JSON primitive issue in ASP.NET?
This post can help you to solve “Invalid JSON primitive: {any-value}” issue when you make a web request from browser to the server.
I can make an assumption that you are either using jQuery or AngularJS light version of jQuery (or some other way) to make an AJAX request from your client to the server. In any of the above case, your could may look similar to the code snippet below.
// a valid JSON object
var dataToLog = {'foo':'foovalue', 'bar':'barvalue'};
$.ajax({
type: 'POST',
url: '/logger/log',
contentType: 'application/json; charset=UTF-8',
data: dataToLog
}).done(() => {
// do something
});
Based on the code above, jQuery might not send it as JSON data but instead serialise it to “foo=foovalue&bar=barvalue” thus you get the error “Invalid JSON primitive: foo”. The code has “contentType” set to “application/json” which means that the data send to the server will follow the JSON format but what is actually sent is a plain JavaScript object which gets serialised as percentile-encoded-string by jQuery.
Just a reminder that – “contentType” is the type of data you are sending to the server. Also, if you don’t set any “contentType” for the ajax method, the default one that jQuery uses is “application/x-www-form-urlencoded; charset=UTF-8”. So, make sure you set the correct type when interacting with the server.
And “dataType” is the format what you are expecting to get back from the server. e.g. json, html, text, etc.
The correct way:
To fulfil our promise, we need to send the data as JSON format. For which we can use the “JSON.stringify” method to wrap the data as string as shown below. The JSON object has a good browser support.
// a valid JSON object
var dataToLog = {'foo':'foovalue', 'bar':'barvalue'};
$.ajax({
type: 'POST',
url: '/logger/log',
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify(dataToLog)
}).done(() => {
// do something
});
Now, ASP.NET will be able to parse the data for you.
