Automatically HtmlEncode strings when the model is serialized with Json.Net

Buda Gavril picture Buda Gavril · May 22, 2017 · Viewed 9.5k times · Source

Is there a way to configure Json.Net to automatically encode all strings like HtmlEncode(myString) when the model is serialized?

Answer

Mohammad Nikravan picture Mohammad Nikravan · Jan 24, 2018

Try this:

var json = JObject.Parse("{'Name':'<script>alert(1);</script>'}");
var serializerSettings = new JsonSerializerSettings()
{
    StringEscapeHandling = StringEscapeHandling.EscapeHtml
};
var result = JsonConvert.SerializeObject(json, serializerSettings);

result will be:

{"Name":"\u003cscript\u003ealert(1);\u003c/script\u003e"}