Is there a way to configure Json.Net to automatically encode all strings like HtmlEncode(myString) when the model is serialized?
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"}
I found a very simple way doing this (WebAPI2).
When you set your object properties, just encode it with below.
myObject.encoded_field = HttpUtility.HtmlEncode(your_html_content)