Is there a way to configure Json.Net to automatically encode all strings like HtmlEncode(myString)
when the model is serialized?
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"}