Newtonsoft.Json.JsonConvert.SerializeObject Like many ASP.NET developers, I use the Newtonsoft library to convert C# objects into JSON. Is this use of Newtonsoft.Json.JsonConvert.SerializeObject secure?

Here is how I use it in a Razor view:

&lt;script type="text/javascript"&gt;
    var json = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model))
&lt;/script&gt;


In Web Forms I might have this in my ASPX:

&lt;script type="text/javascript"&gt;
    var json = &lt;%= Newtonsoft.Json.JsonConvert.SerializeObject(Model)) %&gt;
&lt;/script&gt;
Take the following result :

&lt;script type="text/javascript"&gt;
    var json = { "key" : "&lt;/script&gt;" }
&lt;/script&gt;


Unless you HtmlEncoded your data somewhere, the "&lt;/script&gt;" will break your code. With Html Encoding, the result should look like this :

&lt;script type="text/javascript"&gt;
    var json = { "key" : "&amp;lt;/script&amp;gt;" }
&lt;/script&gt;


To easily encode all string, you can check this solution : http://pastebin.com/R2PWZkUq

Note that this should happen only with object declare inline. JSon coming from Ajax don't have this problem.